我正在创build多个进程, 我需要为每个进程创build两个未命名的pipe道。
对于每个孩子,将使用一个pipe道从父节点获取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: %dn",me); sleep(1); // exit(4); return me * 2; } else if ( child < 0){ // printf("Could not create childn"); } else { children[i] = child; // printf("I have created a child and its pid %dn",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 %dn",children[i],WEXITSTATUS(status)); } return 0; }
我尝试了许多没有成功的事情,而我迷失了方向。 你能帮我继续吗?
python线程内存使用率64位与32位
Linux脚本来检查进程是否正在运行并对结果进行操作
字体文件被系统进程占用
任何帮助表示赞赏! 谢谢。
将一个长整型投射到void *
Android SDK 64位(独立不ADT包)是否存在了?
启动f#与Process.Start交互
强制内存分配在64位Linux上从更高地址(> 4GB)分配
以下是如何为每个子进程设置一个管道,以便每个子进程都可以写入父进程:
由于您需要两个文件描述符为每个孩子,声明:
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])
关闭管道的读取端。
由于每个子进程需要两个管道,所以创建两个数组 – 一个包含写入父级的子级的管道,另一个包含父级写入子级的管道。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。