【发布时间】:2016-11-26 19:30:40
【问题描述】:
目前我正在学习 C,我想用叉子和管道创建一个 n 子 进程,其中 n em> 是输入参数的数字,每个孩子可以与下一个孩子单向交流like this. 我尝试这样做,每个孩子将其 pid 发送给下一个孩子,但如果我创建 3 个孩子,我就得不到我想要的:
- PID:1,i 在循环中:0,接收到:0
- PID:2, i in loop : 1, received : 0
- PID:3, i in loop : 2, received : 0
但我应该得到:
- PID:1,i 在循环中:0,收到:3
- PID:2, i in loop : 1, received : 1
- PID:3, i in loop : 2, received : 2
有时我会从一个随机子节点接收到另一个子节点的值,这是我的代码,我对循环中的多个管道不太满意。
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char * argv[]) {
if(argc != 2) {
fprintf(stderr, "Usage : %s <integer> [> 2]\n", argv[0]);
exit(EXIT_FAILURE);
}
int number_process = atoi(argv[1]);
if(number_process < 2) {
fprintf(stderr, "Usage : %s <integer> [> 2]\n", argv[0]);
exit(EXIT_FAILURE);
}
printf("Création de %d processus pour une élection : \n", number_process);
int i = 0, j = 0, k = 0;
int * t = (int *) malloc((2 * number_process) * sizeof(int));
for(k = 0; k < number_process; k++) {
pipe(&t[2*i]);
}
for(i = 0; i < number_process; i++) {
if(fork() == 0) {
for(j = 0; j < number_process*2; j++) {
if(j != 2*i && j != ((2*i+3)%(number_process*2))) {
close(t[j]);
}
}
close(t[(2*i+1)%(number_process*2)]);
close(t[((2*i+2)%(number_process*2))]);
int pid = (int) getpid();
write(t[(2*i+3)%(number_process*2)], &pid, sizeof(int));
int in = 0;
read(t[i*2], &in, sizeof(int));
printf("%d : %d\n", in, getpid());
exit(EXIT_SUCCESS);
}
}
return (EXIT_SUCCESS);
}
【问题讨论】:
-
你怎么知道代码错了?
-
我用 printf 对其进行了测试,其中显示了 i、当前进程 id 和收到的整数,我应该得到每个孩子的前一个 pid,但我没有得到我应该得到的。跨度>
-
在问题中添加您认为应该得到什么以及实际得到什么。
标签: c pipe fork child-process