如何解决在 C 中使用循环分叉和管道进程
我正在学习 Forking 和 Piping,我清楚地了解如何连接父级和多个子级。
现在我在循环那个 Circle 时遇到了麻烦。
示例如下
父 -- 子 1 -- 子 2 -- 子 3 -- 子 4
'- - - -- - - - - - - - - - - --- ----- - - - - - - - - - - - '
我构建了这一轮计算,我想用相同的过程进行另一次计算。
我希望这一轮永远不会在没有条件的情况下结束(如果 x == 10)
得到结果后,我使用现有管道向孩子 1 发送了另一个数据,但孩子 1 从未回答。
如何在这种情况下进行循环?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>
#define PROCESS_NUM 5
int main(int argc,char* argv[]) {
int pids[PROCESS_NUM];
int pipes[PROCESS_NUM + 1][2];
int i;
int pid;
int end=1;
for (i = 0; i < PROCESS_NUM + 1; i++) {
if (pipe(pipes[i]) == -1) {
printf("Error with creating pipe\n");
return 1;
}
}
for (i = 0; i < PROCESS_NUM; i++) {
pids[i] = fork();
if (pids[i] == -1) {
printf("Error with creating process\n");
return 2;
}
if (pids[i] == 0) {
// Child process
pid = getpid();
int j;
for (j = 0; j < PROCESS_NUM + 1; j++) {
if (i != j) {
close(pipes[j][0]);
}
if (i + 1 != j) {
close(pipes[j][1]);
}
}
int x;
if (read(pipes[i][0],&x,sizeof(int)) == -1) {
printf("Error at reading\n");
return 3;
}
printf("(%d) Got %d\n",pid,x);
if(x==3){
printf("Done!");
if (write(pipes[i + 1][1],sizeof(int)) == -1) {
printf("Error at writing\n");
return 4;
}
printf("(%d) Sent %d\n",x);
}else{
x++;
if (write(pipes[i + 1][1],sizeof(int)) == -1) {
printf("Error at writing\n");
return 4;
}
printf("(%d) Sent %d\n",x);
}
//close(pipes[i][0]);
//close(pipes[i + 1][1]);
return 0;
}
}
// Main process
int j;
for (j = 0; j < PROCESS_NUM + 1; j++) {
if (j != PROCESS_NUM) {
close(pipes[j][0]);
}
if (j != 0) {
close(pipes[j][1]);
}
}
int y = 0;
printf("Main process sent %d\n",y);
if (write(pipes[0][1],&y,sizeof(int)) == -1) {
printf("Error at writing\n");
return 4;
}
if (read(pipes[PROCESS_NUM][0],sizeof(int)) == -1) {
printf("Error at reading\n");
return 3;
}
printf("The final result is %d\n",y);
if (write(pipes[0][1],sizeof(int)) == -1) {
printf("Error at writing\n");
return 4;
}
close(pipes[0][1]);
close(pipes[PROCESS_NUM][0]);
for (i = 0; i < PROCESS_NUM; i++) {
wait(NULL);
}
return 0;
}
解决方法
我想用同样的过程再做一次计算。
我使用现有管道向孩子 1 发送了另一个数据,但孩子 1 从未回答。
这是可以理解的,因为每个孩子都在一次运行后执行 return 0;
- 您没有将它(在循环中)编程为多次读/写。
我希望这一轮永远不会在没有条件的情况下结束(如果 x == 10)
程序不会按照你的希望运行,而是按照你编写它的方式来运行。
如何在这种情况下进行循环?
由于您永远不会将 x 增加到 3 以上,因此永远不会满足此条件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。