gpt4 book ai didi

c - 处理父子子foro/pipes

转载 作者:行者123 更新时间:2023-11-30 17:44:23 25 4
gpt4 key购买 nike

我有一个用管道创建进程的提案,并且我已经构建了 20 个子进程。有用!但最复杂的事情是满足以下要求:

我必须为每个 child 创建一个具有对数的孙子(例如,第2,第4,第6,..),最后我必须为每个孙子创建一个可被6整除的曾孙。(例如,第2,第4,第6,..)6号孙子、12号孙子、18号孙子)

很抱歉,我是 unix 和并发进程的新手。这是我的简单代码作为开始的基础。

代码:

#include <unistd.h>
#include <sys/types.h>
main(){
pid_t pid;
int i, n=20;

for (i=0; i<n; i++) {
pid=fork();
if (pid == 0) break;
}
printf(“\n The father in the process %d is %d”, getpid(),getppid());
}

最佳答案

未经测试,但我认为这符合您的要求:

#include <unistd.h>
#include <sys/types.h>
main(){
pid_t pid;
pid_t spid;
pid_t sspid;
int i, n=20;

for (i=0; i<n; i++) {
pid=fork();
if (pid == 0){
// Son process
if(i%2 == 0){
//Son process && even
spid = fork();
if (spid == 0){
// Grand son process
if(i%3 == 0){
sspid = fork();
if (sspid == 0){
// Great grand son process
} else {
// Grand son process
}
}
}
}
break; // to avoid continuing the for in the child processes
} else {
// Main process
}
}
printf(“\n The father in the process %d is %d”, getpid(),getppid());
}

关于c - 处理父子子foro/pipes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com