c - 处理父子子foro/pipes

标签 c process fork

我有一个用管道创建进程的提案,并且我已经构建了 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/

相关文章:

在 C/UNIX 中创建子进程/杀死进程

process - 将多个 stdout/stderr 合并为一个 stdout

c - fork了10个子进程,父进程如何收集它们的返回值?

python - 如何从 Heroku Node 生成 Python 进程

c - 用于循环条件的 fork() 会产生竞争条件吗?

c - 如何等待子进程并获取其返回值

c - 是否使用 char 未定义行为访问数组元素?

java - 为什么这段 Java 代码的行为与这段 C 代码不同?

c - 这个shellcode是什么意思?

c - 参数类型之间的区别