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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With