7

I can easily start a background process, find its pid and search it in the list of running processes.

$gedit &
$PID=$!
$ps -e | grep $PID

This works for me. But if I start gnome-terminal as the background process

$gnome-terminal &
$PID=$!
$ps -e | grep $PID

Then, it is not found in the list of all running process.

Am I missing something here?

db42
  • 4,184
  • 4
  • 30
  • 36
  • Now (2019) it appears `gnome-terminal` is just one process `gnome-terminal-server` which would make it very hard to manage individual terminal windows through a script. – szmoore Feb 26 '19 at 03:26

3 Answers3

12

If you use the "--disable-factory" option to gnome-terminal it's possible to use gnome-terminal in the way you desire. By default it attempts to use an already active terminal, so this would allow you to grab the pid of the one you launch. The following script opens a window for 5 seconds, then kills it:

#!/bin/bash
echo "opening a new terminal"
gnome-terminal --disable-factory &
pid=$!
echo "sleeping"
sleep 5;
echo "closing gnome-terminal"
kill -SIGHUP $pid
Osmund
  • 736
  • 6
  • 13
6

This appears to be because the gnome-terminal process you start starts a process itself and then exits. So the PID you capture is the pid of the "stub" process which starts up and then forks the real terminal. It does this so it can be completely detached from the calling terminal.

Unfortunately I do not know of any way of capturing the pid of the "granchild" gnome-terminal process which is the one left running. If you do a ps you will see the gnome-terminal "grandchild" process running with a parent pid of 1.

Sodved
  • 7,982
  • 28
  • 39
1

(This is just a footnote) As @Sodved said, gnome-terminal starts a process itself and then exits, there is no way to get the grandchild pid. (See also APUE Chapter 7 why a child process won't re-attach to the grandparent process when its parent process was terminated. )

I found that gnome-terminal instantiates only once, so here is just a short script for your specific task:

GNOME_TERMINAL_PID=`pidof gnome-terminal`

If you don't have pidof:

GNOME_TERMINAL_PID=`grep Name: */status | grep gnome-terminal | cut -d/ -f1`
Xiè Jìléi
  • 12,317
  • 15
  • 72
  • 100