c - fork 命令创建进程树,无法显示 ppids
问题描述
我正在尝试创建一个进程树,如下所示: F \ |\1 \ | |\3 | \4 \2 F 和 1 将等待他们的孩子被终止。不知何故,所有的父母 pid 都被表示为 1。其次,我认为是“所有人的父亲”的过程 - F 似乎不是真正的父亲。这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main (){
int status;
pid_t child_1;
child_1 = fork();
if(child_1 == 0){ //This is the child 1 process.
printf("child 1:%d, %d\n", getpid());
int returnStatus;
waitpid(child_1, &returnStatus, 0);
pid_t child_3 = fork();
if(child_3 == 0){ //This is the child 3 process.
printf("child 3:%d, %d\n", getpid());
printf("parent child 3:%d\n", getppid());
}
else if(child_3 > 0){ // This is the father of child 3.
pid_t child_4 = fork();
if(child_4 == 0){ //This is the child 4 process.
printf("child 4:%d, %d\n", getpid());
printf("parent child 4:%d\n", getppid());
}
}
}
else { // This is the father of all processes.
int returnStatus;
waitpid(child_1, &returnStatus, 0);
printf("FATHER OF THEM ALL:%d\n", getpid());
pid_t child_2 = fork();
if(child_2 == 0){ // This is the child 2 process.
printf("child 2:%d, %d\n", getpid());
}
}
return 0;
}
解决方案
建议类似于以下的布局:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main ( void )
{
pid_t pid1 = fork();
switch( pid1 )
{
case -1:
perror( "fork for child1 failed" );
exit( EXIT_FAILURE );
break;
case 0:
printf( "child1 pid: %d\n", getpid() );
pid_t pid2 = fork();
switch( pid2 )
{
case -1:
perror( "fork for child2 failed" );
exit( EXIT_FAILURE );
break;
case 0:
printf( "child2 pid: %d\n", getpid() );
exit( EXIT_SUCCESS );
break;
default: // in child 1
{ // braces so can have data declaration
int status2;
waitpid( pid2, &status2, 0 );
exit( EXIT_SUCCESS );
break;
}
}
break;
default: // in original parent
{
int status1;
waitpid( pid1, &status1, 0 );
}
}
return 0;
}
正确处理child1和child2。在default
child1 的情况下,可以插入 child 1 的第 3 个和第 4 个子进程的代码
推荐阅读
- java - Java 8 多键分组
- javascript - 在许多输入中加载和预览图像
- python - 如何删除tkinter中按钮之间的空间?
- console-application - 带有 C# 的 SendGrid V3 api 无法从控制台应用程序发送邮件
- java - Gson - CustomObject 内的嵌套对象 - java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap 无法转换为 java.util.List
- python - 基于条件的新列值
- java - c ++中用于联合查找的自引用结构
- python - blpapi.exception.UnsupportedOperationException:快照没有订阅管理端点(0x00080013)
- css - 根据img覆盖svg响应
- r - 如何在 ggplot2 中保存带有特殊字符的 R 图?