J.R.
J.R.

Reputation: 809

why I cannot kill the process group with this c code?

In the main parent process I called :

killpg(child_group, SIGKILL);

in the child process, i set the child group as:

setsid();
child_group = getpgrp();

But I checked the processes, ps shows the process group was not killed. What did I do wrong?

Upvotes: 3

Views: 2484

Answers (1)

jfMR
jfMR

Reputation: 24738

In the parent process:

killpg(child_group, SIGKILL);

How did you actually get child_group?

Doing the following in the child process for that purpose is pointless:

child_group = getpgrp();

That is because this child_group is just a copy in the child process (i.e.: the child_group in the parent process doesn't get modified)


SIGKILL has to be send to the PGID that corresponds to the child's PID, because it becomes a process group leader by means of setsid(). That is, as the argument for killpg() you should use the pid_t returned to the parent process by the call to fork().

Be sure killpg() gets called by the parent after setsid() is (successfully) returned in the child (i.e.: after the child has become a process group leader and not before).


A minimal example:

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

void parent(pid_t pid) {
    killpg(pid, SIGKILL);
}

void child(void) {
    if (-1 == setsid())
        return;

    while(1) {
        sleep(1);
        printf("child\n");
    } 
}


int main() {
    pid_t pid;
    switch ((pid=fork())) {
    case 0: // child
        child();
        break;

    default: // parent
        // wait some time to let setsid() complete
        sleep(5);
        parent(pid);
    }

    return 0;
}

Upvotes: 4

Related Questions