简体   繁体   English

子进程叉3秒后会自行杀死

[英]child process kill itself after 3 seconds in fork

I have a fork function that creates a child process and a parent process 我有一个fork函数,它创建一个子进程和一个父进程

I would like the child process to kill itself as soon as 3 seconds passes, using the kill(child, SIGKILL) function, that means withoutt using the exit() function. 我希望子进程在3秒后使用kill(child,SIGKILL)函数杀死自己,这意味着无需使用exit()函数。 However I am not sure of the implementation. 但是我不确定执行情况。 I tried using the kill function signal right after the while loop end, but it does not kill the child. 我尝试在while循环结束后立即使用kill函数信号,但是它不会杀死孩子。

I tried to put it at the end of the main function, but it kills the child before 3 seconds passes 我试图将其放在主函数的末尾,但是它在3秒过去之前杀死了孩子

I tried to put it in a function that is called as soon as the while loop ends, but it did not kill the child 我试图将其放在while循环结束时立即调用的函数中,但是它没有杀死孩子

How can I do this with a better implementation that actually works ? 我如何才能通过一个更好的,实际可行的实现来做到这一点?

here is my code with comments available: 这是我的代码并提供注释:

int main()
{
    pid_t pid;
    int seconds = 3;
    int child;

    pid = fork();
    int i = 0;



    if(pid == 0)          //this is the child
    {
        child = getpid();

        while( i <= seconds)
        {
            cout << " second " << i << endl;
            sleep(1);
            i++;

        }
        killChild(child);     //function called after 3 seconds passes

    }

    else if(pid < 0)        //error statement
    {
        cout << " we have an error " << endl;
    }

    else                //parent if pid > 0
    {
        cout << " I am the parent " << endl;
        sleep(1);

    }

    //kill(child, SIGKILL)  placing it here will kill child before seconds passes

}


void killChild(int child)       //function to kill child (NOT KILLING IT)
{
    kill(child, SIGKILL);
}
 void killChild(int sigNum)//Argument here is signal number
    {
        kill(getpid(), SIGKILL);
    }  


  int main()
    {
        pid_t pid;
        int child;
        pid = fork();

        if(pid == 0)//this is the child
        {
            signal(SIGALRM,killchild)
            child = getpid();
            alarm(3); //set alarm for 3 seconds
            while(1); //continue to loop until 3 seconds passed
        }

        else if(pid < 0)//error statement
        {
            cout << " we have an error " << endl;
        }

        else//parent if pid > 0
        {
            cout << " I am the parent " << endl;
        }
    }

   After 3 seconds, alarm() function will generate SIGALRM and on this signal egneration, your killchild() function will be called and kill child. 

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM