【问题标题】:Running in same child process two times在同一个子进程中运行两次
【发布时间】:2020-12-14 16:14:43
【问题描述】:

我可以在同一个分叉中在同一个子进程中运行两次吗?例如。

pid_t pid;
pid = fork();
if (pid == 0){
    some code here
}else{
    some code here
}
wait(NULL)
if (pid ==0){
    some code here
}else{
    some core here
}

【问题讨论】:

  • if/else外的代码在父子节点中运行。
  • 这就是我想要实现的:首先,如果我想先运行子代码,然后通过管道将值传递给父级,如果值为 ex = 则检查父级0,然后再次将消息“value is 0”或“value is ~=0”传递给孩子并将其打印给孩子

标签: c linux fork


【解决方案1】:

当您离开if/else 时,代码会在父子节点中运行。下一个if/else 再次切换到每个中的不同代码。

pid_t pid;
pid = fork();
if (pid == 0){
    // child code here
}else{
    // parent code here
}
wait(NULL) // runs in both
if (pid ==0){
    // more child code here
}else{
    // more parent code here
}

除非子进程fork另一个子进程,否则子进程中的wait(NULL)会立即返回(它会返回-1并将errno设置为ECHILD以表示它没有子进程等待)。但是在父进程中它会等待子进程退出。所以第二个if/else 块将立即在子进程中运行,而在子进程退出之前它不会在父进程中运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多