rovio
rovio

Reputation: 11

How to avoid killing child process early?

#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#define MAX_PIDS 28

volatile pid_t *pids;

void kPid(int x)
{
    int c;
    for (c=0; c<10; c++) {

    if (pids[c] == x)
    {   
        int status = 0;
        pids[c] = wait(&status);
    }
    else {
        continue;
    }
  }
}



int main(int argc, char **argv)
{
  int c;
  pid_t pid;
  pids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
              MAP_SHARED | MAP_ANONYMOUS, -1, 0);

  memset((void *)pids, 0, MAX_PIDS*sizeof(pid_t));
  for (c=0; c<10; c++) {
    pid = fork();
    if (pid == 0) {
      exit(1);
    } else if (pid < 0) {
      perror("fork failed");
    } else {
      pids[c] = pid;
    }
  }

  int t;
  char test[50];
  snprintf(test,sizeof(test),"ps -ef | grep defunct",pids[c]);
  system(test);
  printf("Kill child: ");
  scanf("%d",&t);
  kPid(t);
  system(test);
  exit(0);
}

Now when i use command: snprintf(test,sizeof(test),"ps -ef | grep defunct",pids[c]);

It shows that processess are defunct, how to avoid this? i know that "exit(1);" kill the process but what can i put instead of this? I want to be able to kill the process later

Upvotes: 1

Views: 86

Answers (1)

Ctx
Ctx

Reputation: 18420

The easiest way to avoid defunct processes is to ignore SIGCHLD:

signal(SIGCHLD, SIG_IGN);

Otherwise, wait for the child termination with waitpid(). It mainly depends, if you want to know when a child is terminated and what its exit code is. If you do not need that information, go with the signal-method

Upvotes: 1

Related Questions