如何两次调用子进程

时间:2019-03-21 18:40:34

标签: c process

有什么方法可以使子进程两次运行其代码?

例如,如果我们有此代码

pid_t child;
child=fork();
if (child<0) printf("error");
else if (child==0) printf("Hello world, I am the child");
else printf("This is the father");

else之后,我怎么称呼孩子以便再次打印“ Hello world ...”?

2 个答案:

答案 0 :(得分:0)

我只是在这里 猜测 ,但是也许您希望子进程自己运行多个语句?然后,您可以通过将它们全部放在if (child == 0)块中来做到这一点:

if (child == 0)
{
    // Here you can have as many statements as you want
    // The process will continue to run until you explicitly call exit
    // or until you return from the main function

    // If you need to do multiple things, then my suggestion is that
    // you put this code in a function that you call
    // Then when the function returns you call exit to end the process

    exit(0);  // Exit the child process only, the parent can still continue
}

答案 1 :(得分:-1)

您有一个“子”变量,该变量存储fork()函数的返回值(可能是进程ID,但是pid_t能够存储您希望存储的任何带符号的32位int)。然后,将此值与int(0)进行比较。如果要再次打印“ Hello world ...”,则只需使用printf()或if(...)printf()添加一行代码。 希望我理解您的要求并能够提供帮助。