• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4809
  • Last Modified:

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?
0
chsalvia
Asked:
chsalvia
  • 2
1 Solution
 
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
 
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
 
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

Featured Post

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now