14

So I keep reading everywhere that this command should terminate all child processes of the parent process:

kill -- -$$

Using a negative ID with the kill command references a PGID and from the examples I have seen it appears the PGID of child processes should be the PID of the parent but its not the case on my system.

On my system the PGID of the child is the same as the PGID of the parent script which turns out to be bash.

What's going on here? Were the examples wrong or is my system set up differently?

What I need to achieve is to terminate child processes without terminating the parent so I don't want to send a kill signal to the PGID the parent is in.

1 Answer 1

12

When a process is forked, it inherits its PGID from its parent. The PGID changes when a process becomes a process group leader, then its PGID is copied from its PID. From then on, the new child processes it spawns, and their descendants, inherit that PGID (unless they start new process groups of their own).

In a shell with job control, such as most interactive shells, each job is put in its own process group. If you run a shell script, the shell process running the script will be the group leader, and the PGID will equal its PID.

In a shell without job control, such as most shells used to run scripts, commands are run in the shell's process group.

The syntax kill -- -N kills all the processes in the group with PGID = N. You can't use it with an arbitrary PID, only the PID of a process group leader, since that's the PGID. This is essentially how the shell's

kill %jobid

syntax works -- it internally translates %jobid to the PGID of the job and sends the signal to that PGID.

There's no simple way to run a script in its own process group from another shell script. See How to set process group of a shell script for some suggestions, though.

7
  • Are you saying that a shell with or without job control does the same thing?
    – TCZ8
    Jun 25, 2014 at 21:20
  • 1
    No. A shell with job control starts a new process group for each job. A shell without job control does not start a new process group for each job, it runs them in its own process group.
    – Barmar
    Jun 25, 2014 at 21:23
  • wow.. I didn't read that right the first time. So I guess what I want is to turn on job control? Would that ensure that the childs have a PGID matching the PID of the parent script? Or will each child get their own unique PGID?
    – TCZ8
    Jun 25, 2014 at 21:26
  • I found some docs online on job controlls, ill go through that. Thanks for your help Barmar.
    – TCZ8
    Jun 26, 2014 at 12:32
  • 1
    With job control, each child gets its own PGID. Without job control, they inherit the PGID of the parent. But the parent might have inherited its PGID from its parent, if it's not a process group leader.
    – Barmar
    Jun 26, 2014 at 18:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .