我正在创建多个进程,我需要为每个进程创建两个未命名的管道。
对于每个孩子,将使用一个管道从父母那里获取int值;一个用于将int数组发送到父数组。家长会做一些事情,而从孩子那里获取新数据。
基本代码:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // for reaching unix operations
int main(int argc, char *argv[]){
pid_t main = getpid();
int N = 30;
int i;
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);
}
}
// The child never reaches here
for(i = 0; i < N; i++){
int status;
waitpid(children[i], &status, 0);
printf("Process %d exited with return code %d\n", children[i], WEXITSTATUS(status));
}
return 0;
}
我尝试了许多没有成功的事情而且我迷路了。你能帮我继续吗?
任何帮助表示赞赏!谢谢。
答案 0 :(得分:8)
这里是如何为每个子进程设置一个管道,以便每个子进程写入父进程:
由于每个孩子需要两个文件描述符,因此声明:
int fd[2 * N];
适当地初始化它们:
for (int i = 0; i < N; i++) {
pipe(&fd[2*i]);
}
在i
个子进程中,使用:
write(fd[2*i + 1], write_buffer, SIZE)
写入父级,并在父级中使用:
read(fd[2*i], read_buffer, SIZE)
从i
孩子那里读取。
关闭管道:
在i
个孩子的内部,您可以使用
close(fd[2*i])
马上,因为你只是在写作。在你完成了写电话
之后close(fd[2*i + 1])
关闭管道的写入端。
父母的情况是平行的:当你从i
孩子那里读书时,你可以
close(fd[2*i + 1])
马上,因为你没有写作,并且在你完成阅读电话之后
close(fd[2*i])
关闭管道的读取端。
由于每个子进程需要两个管道,因此创建两个数组 - 一个包含写入父项的子项的管道,另一个包含父项写入子项的管道。