在fork

时间:2016-03-09 17:33:30

标签: c++ fork

我有一个fork函数,用于创建子进程和父进程

我希望子进程在3秒后自动终止,使用 kill(子,SIGKILL)函数,这意味着不使用 exit()功能。但是我不确定实施情况。我尝试在while循环结束后立即使用kill函数信号,但它不会杀死孩子。

我试图把它放在主要功能的末尾,但它会在3秒钟之前杀死孩子

我试图将它放在while循环结束时调用的函数中,但它没有杀死孩子

如何通过更好的实施方式实现这一目标?

这是我的代码,提供了评论:

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);
}

1 个答案:

答案 0 :(得分:1)

String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";
System.out.println(new SimpleDateFormat(pattern).format(new Date()));

希望这有帮助!

相关问题