Question

In my parent process, I have created a child process which executes system("find / -print"). From inside the parent, when I try to kill this child process using kill(childProcPID, SIGTERM), it doesn't get terminated immediately. system command keeps on printing the output on console.

Here is the example code:

int main(void) {

    pid_t childProc = fork();
    switch (childProc) {
    case -1:
        perror("fork() error");
        exit(EXIT_FAILURE);
    case 0:
        system("find / -print");
        printf("if I use kill(pid, SIGTERM) control doesnt reach here");
        exit(EXIT_SUCCESS);
    default:
        ;
        int i = 500000;

        //No a great way to put sleep
        //but its just temp
        while (i != 0) {
            --i;
        }

        kill(childProc, SIGTERM);
        break;
    }

    printf("Exit!!!!!!");
    return EXIT_SUCCESS;
}

Please let me know what I am doing wrong or is the right way to kill a child ?

Was it helpful?

Solution 2

try setting the session id and killing the process group instead (man 2 kill)

int main(void) {

pid_t childProc = fork();
switch (childProc) {
case -1:
    perror("fork() error");
    exit(EXIT_FAILURE);
case 0:
    setsid();
    system("find / -print" );
    printf("if I use kill(pid, SIGTERM) control doesnt reach here");
    exit(EXIT_SUCCESS);
default:
    sleep(1);
    kill(childProc*-1, SIGTERM);
    break;
}

printf("Exit!!!!!!");
return EXIT_SUCCESS;
}

this more or less works. The caveat is that there's a bit of a race in that the parent has to give the child time to setsid(), hence the sleep.

Hope that helps.

OTHER TIPS

The system function will itself create a child process to execute the command (and then block until that child process terminates). What you've done is kill the child process that calls system, but not the child process that system has spawned.

First, you should be checking the result that you get back from kill() -- if you get 0 back, the operation succeeded. If you get -1 back, though, check the global variable errno to see what the problem was.

If the signal is being sent successfully, the only thing you can do is make sure that you're sending the signal that you intend. As @Till points out in a comment, sending SIGKILL instead of SIGTERM will be more effective because the OS handles the former and the target process cannot ignore it.

In any case, realize that interacting with other processes is usually an asynchronous process -- the target process probably won't be terminated by the time kill() returns no matter what you do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top