我有一个用管道创建一个进程的建议,我已经构建了 20 个子进程。它有效!但最复杂的问题是满足以下要求:
我必须为每个孩子创建一个带有配对编号的孙子(c.e. 2nd、4rd、6th,..)最后,我必须为每个孙子创建一个可被 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());
}