How to kill a child process by the parent process?

前端 未结 3 1919
野的像风
野的像风 2020-12-08 04:32

I create a child process using a fork(). How can the parent process kill the child process if the child process cannot complete its execution within 30 seconds?

3条回答
  •  眼角桃花
    2020-12-08 05:26

    Try something like this:

    #include 
    
    pid_t child_pid = -1 ; //Global
    
    void kill_child(int sig)
    {
        kill(child_pid,SIGKILL);
    }
    
    int main(int argc, char *argv[])
    {
        signal(SIGALRM,(void (*)(int))kill_child);
        child_pid = fork();
        if (child_pid > 0) {
         /*PARENT*/
            alarm(30);
            /*
             * Do parent's tasks here.
             */
            wait(NULL);
        }
        else if (child_pid == 0){
         /*CHILD*/
            /*
             * Do child's tasks here.
             */
        }
    }
    

提交回复
热议问题