Linux - Kill Child Processes

I'm trying to figure out the easiest way to have a parent process send a signal to all of its children in a C program written in a Linux environment.

Obviously, the easiest way to signal a particular child process is using the kill system call, and passing it the PID of the child.  But if you don't have the PID of the child, or you want to send a signal to ALL children, is there an easy way to do it?

I realize that you can pass PID 0 to kill(), which will send a signal to every process in the current process group.  Unfortunately, this includes the parent as well.  (I could have the parent block signals, and then have all children unblock, but this seems cumbersome.)

The man page for kill() also says the following:

"If pid is less than -1, then sig is sent to every process in the process group -pid."

I'm not sure what this means.  What does "in the progress group minus pid" mean?  Regardless, I tried passing PID -2 to kill, and it had no effect at all.

So, what is the best way to have the parent process send a signal to all of its children?
chsalviaAsked:
Who is Participating?
 
ravenplCommented:
If You haven't recorded pids of Your children - You can only kill the process group (as You noticed, 0 means current, -X means group where process with pid=X belongs).
Refer also: man 2 killpg

But remember to create Your master process group leader. Refer setpgrp() setsid()
0
 
ozoCommented:
How did you create the child that you don't have the PID?
Can you set the process group when you create the child?
0
 
eagerCommented:
You should keep track of PIDs for children.  One common way is to have the child process save it's PID somewhere, like /var/run/<program>.pid.  Another process (or the parent) can look in this directory to find the PID of the program.

Killing all of the processes in a process group will kill the parent as well as children.  That may not be what you wanted.  

Also take a look at "killall" or "pkill".  Both commands will kill a process based on the command name.  But I would never put those in a script -- you never know what might be running which has a similar name.  
0
 
ozoCommented:
Can you detach a process to serve as the parent of all the processes you want to kill?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.