Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill child of fork?

Tags:

c

fork

I have the following code which create a child fork. And I want to kill the child before it finish its execution in the parent. how to do it?

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

int i;

main (int ac, char **av)
{
  int pid;

  i = 1;

  if ((pid = fork()) == 0) {
    /* child */
    while (1) {
      printf ("I m child\n");
      sleep (1);
    }
  }
  else {
    /* Error */
    perror ("fork");
    exit (1);
  }
  sleep (10)

   // TODO here: how to add code to kill child??

}
like image 932
MOHAMED Avatar asked Nov 07 '12 16:11

MOHAMED


3 Answers

See kill system call. Usually a good idea to use SIGTERM first to give the process an opportunity to die gratefully before using SIGKILL.

EDIT

Forgot you need to use waitpid to get the return status of that process and prevent zombie processes.

A FURTHER EDIT

You can use the following code:

kill(pid, SIGTERM);

bool died = false;
for (int loop; !died && loop < 5 /*For example */; ++loop)
{
    int status;
    pid_t id;
    sleep(1);
    if (waitpid(pid, &status, WNOHANG) == pid) died = true;
}

if (!died) kill(pid, SIGKILL);

It will give the process 5 seconds to die gracefully

like image 110
Ed Heal Avatar answered Nov 07 '22 12:11

Ed Heal


Send a signal.

#include <sys/types.h>
#include <signal.h>

kill(pid, SIGKILL);

/* or */

kill(pid, SIGTERM);

The second form preferable, among other, if you'll handle signals by yourself.

like image 30
md5 Avatar answered Nov 07 '22 11:11

md5


Issue kill(pid, SIGKILL) from out of the parent.

like image 42
alk Avatar answered Nov 07 '22 10:11

alk