我正在尝试编写排序功能。
这个函数可以分叉许多孩子来帮助自己对给定的输入进行排序。
当我的函数只有一个孩子时,它很容易使用pipe()
。我只是创建
int fd[2];
然后一切都很好,但是当有很多孩子时我不知道该怎么办。我应该创建fd[Children*2]
管道还是fd[2]
就足够了?
我如何使用这些管道与我想要的孩子沟通(因为有很多孩子)?
答案 0 :(得分:0)
我的主要进程将fork子,这只是代码的一部分,我正在分析孩子并将他们的pid变成pid数组
pid_t main = getpid();
int N = 30;
pid_t* children = (pid_t*) malloc(sizeof(pid_t) * N);
for(i = 0; i < N; i++){
pid_t child = fork();
if ( child == 0){
pid_t me = getpid();
printf("I'm a child and my pid is: %d\n", me);
sleep(1);
// exit(4);
return me * 2;
} else if ( child < 0){
// printf("Could not create child\n");
} else {
children[i] = child;
// printf("I have created a child and its pid %d\n", child);
}
}
答案 1 :(得分:0)