How can I kill all processes of the program?

I wrote a program that spawns some processes using fork (). I want to kill all children and mothers if there is a mistake. If I use exit (EXIT_FAILURE), only the child process is killed.

I'm thinking about the system ("killall [program_name]"), but there must be a better way ...

Thanks everyone! Lennart

+1


a source to share


4 answers


On UNIX, send SIGTERM or SIGABRT or SIGPIPE or sth. like a mother's process. This signal will then be automatically sent to all clients unless they explicitly block or ignore it.

Use getppid()

to get the PID for sending a signal, and kill()

for sending a signal.



getppid () returns the process id of the parent of the calling process.

The kill () system call can be used to send any signal to any process group or process.

Note: 1. Use system

is evil. Use internal functions to send signals. 2. killall

would be even more evil. Let's consider several instances of your program at once.

+5


a source


See How do I make a child process die after exiting a parent?

There is a call on Linux prctl()

that is explicitly designed to send a signal to all child processes when a parent dies for whatever reason.



I need to check and can't get it done when I'm in the second one, but I'm really not sure what ypnos's statement is about SIGPIPE

, SIGTERM

and SIGABRT

applies to all children correctly.

However, if you use kill(-ppid)

(note the minus sign), then while the children are still in the parent process group of the process, the kernel delivers any signal to all children.

+2


a source


If your parent process does not start on the command line, it may not be the leader of the process group, such as deamon.

To ensure that your parent process is the leader of the process group, call setid () while your process is initializing.

Then in your child process if you want to dump all processes:

pgid = getpgid (); kill (pgid, 15);

You can also do tricks, like telling all your siblings to suspend:

kill (pgid, 20);

And to resume:

kill (pgid, 18);

+1


a source


Consider the suicidal approach - setting alarm()

at the beginning of the process (of both parent and child) with some positive number of seconds. If the computation is complete within this time and there is no error, call alarm(0)

to cancel the timer; SIGALRM

will kill the process otherwise (unless you explicitly catch or ignore it).

Well, do a case against that, not just vote :)

0


a source







All Articles