Home > OS >  Can't kill all child processes using SIGTERM
Can't kill all child processes using SIGTERM

Time:11-25

My program has the following parent child layout:

int main() { 

std::vector<pid_t> kids;
pid_t forkid = fork();

if (forkid == 0) {
//child process
    pid_t fork2 = fork() 
    if (fork2 == 0) {
      // child process 

     }else {
      //parent
      kids.push_back(fork2);
     }
}else {
// code here
   kids.push_back(forkid);
}

// Not killing the fork2 process - only the first process(forkid) is terminated

for (pid_t k : kids) {
    int status;
    kill(k, SIGTERM);
    waitpid(k, &status, 0);
}


  }

I am not able to kill the child process (fork2) - the first process gets terminated. The kids vector seems to only contain the process id of the first process. Never gets the pid of the child process. What am I doing wrong here. Any help will be appreciated. Thanks.

CodePudding user response:

std::vector<pid_t> kids;
pid_t forkid = fork();

fork() creates a complete duplicate image of the parent process as its child process. Emphasis on: duplicate.

This means that, for example, the child process has its very own kids vector, that has nothing to do, whatsoever, with the parent process's original kids vector.

Since this is the very first thing that happens in main, this is really no different than you running this executable twice, individually as two distinct and separate processes, instead of forking off a process. You can't expect the kids vector in one of the two processes to have any effect on the kids vector in the other one.

The first child process creates a 2nd child process, and also adds the 2nd child process's pid into its own kids vector. But that's just the first child process's kids vector.

The only process id that the original parent process's kids vector ends up having is the first child's process it, so that's all you get to SIGTERM.

Your options are:

  1. Restructure your logic so that both child process get created by the parent process, so it, alone, puts their process ids into its kids vector.

  2. Instead of using fork use multiple execution threads, and the same process. However, neither std::vector, nor any other C library container is thread safe. A massive pile of code will need to be written to properly synchronize the threads, in order for things to work themselves out correctly (not to mention that the analogue for the SIGTERM, with respect to multiple execution threads, needs to be invented in some way).

The simplest alternative is the first one.

  • Related