Search code examples
cunixprocesssigkill

Kill process tree without printing 'Killed' in C


I'm trying to kill an entire process tree in C. I am able to do this, however when I run the code, it prints "Killed". I don't want this. Is there any way I can achieve the same result without printing "Killed"?

This is the code I am using:

#define _POSIX_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

#include <unistd.h>
#include <sys/wait.h>

int main() {
    int pid = fork();
    if (pid == 0) {
        sleep(2);
        printf("child printf\n");
    } else {
        sleep(1);
        kill(-getpid(), SIGKILL);
    }

    return EXIT_SUCCESS;
}

I am compiling this with gcc -std=c99 -Wall test.c. When I run ./a.out, this is the output:

Killed

If I change the sleep(1) to a sleep(3), this is the output:

child printf
Killed

In both cases I want the Killed line removed.

Note: In the real code, the child process will be execve'd with another. There will be multiple child procceses. Because they can have children themself, doing kill(pid, SIGKILL) won't work.


Solution

  • According to the kill manual page, a pid value less than -1 (which you will pass) means

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

    That is, you will kill the parent process (and which will produce the message) since you pass -getpid(), but you will not kill any other child process.

    If you want to kill a specific process, pass its exact process id (in your case pid) to the kill call.

    If you want to kill all child processes then you need to create a process group, so all children becomes a member of it, and kill all processes in the process group (by passing the pid 0). Note that this will call the parent process as well.

    If you want to kill the child processes, but not the parent process, create a proxy-process which creates a new process group, and have this proxy-process create the child processes. Then kill the proxy-process process group.

    Anyway, the solution to your problem is to not kill the parent process, but let it exit normally.