Home > Software design >  Killing child process one by one
Killing child process one by one

Time:02-17

First, I create the multiple number of child process using the for loop. Then, I put all of the child process into sleep(by adding infinite sleep block).

void kill_child(int sig);

int main(void){
     signal(SIGHUP, kill_child);
     for(int i = 0; i < max_child; i  ){
        pid_t id = fork();
        if(id == 0){
            printf("Hi, i am a child\n");
            while(1){sleep(1);}
        }
        if(id == 1){
            printf("Hi, i am a parent\n");
       
        }
     }
     
}

void kill_child(int sig){
     if(sig==SIGHUP){
         //do stuff to kill single child
     }
}

What am I planning to do next, send the kill -HUP parent from terminal to kill the child process one by one. At the end, if no child process terminate the program.

I just want to know is there any way to kill single child at a time under condition like this.

CodePudding user response:

I Think you can use an array with global scope to safe children's pid and then use it into the function kill_child calling: int kill(pid_t pid, int sig). Inside kill_child, I think you can send SIGKILL to children or redefine behavior with signal function if you want to send SIGTERM. This can be a solution. Aniway, I noticed something that can be improved (in my humble opinion) in your code:

  1. I'm not sure that your program will print "Hi, i am a parent\n" because you can't be sure that at least one child has pid = 1(unless you are sure of it for other reasons)
  2. The while loop create a lot of overhead because every second you reactivate a process and this process sooner or later take the CPU only for call sleep to wait one second

I hope I have helped you!

  • Related