21

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??

}
Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 3
    `fork()` returns a `pid_t`, not an `int`, so you should declare your variable as such. – Niklas B. Nov 07 '12 at 16:24
  • 1
    Unrelated to the original question: When fork returns a new process is spawned (in case of success) and both parent and child continue execution from the point where `fork` has been called. pid = 0 for a child process (well, it can always get it via getpid()) and pid > 0 for a parent process. The error is only when fork returns -1. In your code you are treating a "parent process" part as an error. – Maksim Skurydzin Nov 07 '12 at 16:35
  • 1
    possible duplicate of [How to kill a child process by the parent process?](http://stackoverflow.com/questions/6501522/how-to-kill-a-child-process-by-the-parent-process) – goozez Jul 18 '14 at 08:57

3 Answers3

16

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
14

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.

md5
  • 23,373
  • 3
  • 44
  • 93
5

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

alk
  • 69,737
  • 10
  • 105
  • 255