0

I am forking a child, and trying to kill it.

pid_t *child_pid;

int main(){
    child_pid = mmap(NULL, sizeof(pid_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);$

    int a = fork();
    if (a != 0) {
            printf("child @ %d\n", a);
            *child_pid = a;
            system("sleep 100");
    } else {
            sleep(1);
            printf("Trying to kill %d\n", *child_pid);
            int ret = kill(*child_pid,SIGKILL);
            printf("killled with %d\n", ret);
    }
}

However, the kill command gets stuck at:

child @ 4752 
Trying to kill 4752

In the meantime, calling ps shows this:

4752 pts/4    00:00:00 simple <defunct>
bob
  • 152
  • 6

2 Answers2

0

The child process is dead, it's just that the process entry will hang around until someone collects the exit code.

If the parent doesn't do it, it will eventually be inherited by init, which will reap it at some point.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • But how does Ctrl-C force the process to exit ? – bob Jul 27 '15 at 10:05
  • @bob Ctrl-C is handled by your shell, which keeps tracks of the process IDs of its children. If you press Ctrl-C, the shell does a kill(SIGTERM) on the process (your 'simple'), 'simple' exits, the shell gets notified by a signal, then the shell collects the exit status with waitpid(). It's a fairly complex process... The key element is wait()/waitpid() here. – JvO Jul 27 '15 at 10:28
0

You are killing yourself. fork() returns 0 if you are in the forked process, or the child process id (PID) in the 'master' process.

So, the upper branch of your if() clause is performed in the master process, where you copy the child's process ID (stored in a) to child_pid.

In the lower branch you are in the child process, where take the child_pid, which is your own and then happily kill() yourself... That's why you never get the line 'Killed with...'

As paxdiablo pointed out, since this is a child process it will remain a zombie until you fetch the exit status with wait() or the master process exits.

BTW, I'm not sure what you want to do with this code:

  • If you want to exit the child process gracefully you can just do an exit().
  • If you want to kill your child process, keep track of the child PID (returned by fork()) and then kill() it from your master process.
  • If you want to kill the master process from your child (odd as that may sound) be careful, as that may take the child process(es) with it. You have to detach the child process from the master process (see the manual page for daemon()).
JvO
  • 3,036
  • 2
  • 17
  • 32