在 C 中管道传输来自多个子级的结构



背景:

我正在做一项学校作业,任务是对图像进行子采样,并使用过程来模拟"服务器"对图像中的某些像素进行计算。我非常接近让作业工作,但我在阅读和写入结构时遇到了一个奇怪的错误,从多个孩子到父母的管道。

为了说明这一点,我试图做一个更简单的例子,没有所有的图像子采样内容。我发现我无法获得这个非常简单的代码来打印数字 1-50,所以也许这段代码中有一个错误,我只是没有意识到或理解正确。

<小时 />

代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

// Create a struct to hold the index
struct Thing {
int index;
};
int main() {
pid_t pid;
int processLabel;
int c2p[2];
int p = 2;
// create p number child processes
for(processLabel = 0; processLabel < p; processLabel++)
{
if(pipe(c2p) == -1)
{
perror( "pipe Failed" );
continue;
}
pid = fork();
if(pid  == 0) {
break;
}
}
if (pid == 0) { // child process
int count = 0;
// close read from parent process
close(c2p[0]);
for(int i = 0; i < 50; i++){
// write the index to parent depending on what child process we are in
if(count % p == processLabel){
struct Thing test;
test.index = count;
write(c2p[1], &test, sizeof(test));
}
count++;
}
close(c2p[1]);
}
else { // parent
close(c2p[1]);

// read structs from child processes
for(int i = 0; i < 50; i++){
struct Thing test;
read(c2p[0], &test, sizeof(test));
printf("index: %dn", test.index);
}
close(c2p[0]);
}
return 0;
}

if(count % p == processLabel)的目的是在我的实际代码中,用于子进程各自对图像的某些部分进行计算的赋值。它是"模拟"服务器对图像的不同部分进行计算,以加快图像子采样的速度。

<小时 />

输出:

p为 2 时,我从此代码收到的输出如下:

index: 1
index: 3
index: 5
index: 7
index: 9
index: 11
index: 13
index: 15
index: 17
index: 19
index: 21
index: 23
index: 25
index: 27
index: 29
index: 31
index: 33
index: 35
index: 37
index: 39
index: 41
index: 43
index: 45
index: 47
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49
index: 49

如您所见,当我希望它打印出 0 到 49 时,它只会打印出父级中的奇数。有趣的是,当我将进程数的值更改为 1 时p代码工作正常,计数从 0-49。

感谢您对此的任何帮助!

您正在创建两个管道,但只读取一个管道。

简单的解决方案:将呼叫移动到循环之外pipe

我相信如果写入小于一定大小,则保证写入是原子的,因此只要结构足够小,这是安全的。

最新更新