【发布时间】:2020-04-01 12:17:47
【问题描述】:
背景:
我正在做一项学校作业,任务是对图像进行二次采样并使用进程来模拟“服务器”对图像中的某些像素进行计算。我非常接近让任务开始工作,但我遇到了一个奇怪的错误,即读取和写入一个带有从多个子级到父级的管道的结构。
为了说明这一点,我尝试做一个更简单的示例,而不需要所有图像二次采样。我发现我无法获得这个非常简单的代码来打印数字 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: %d\n", 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 时,它只打印父项中的奇数。有趣的是,当我将 p 进程数的值更改为 1 时,代码有效正确地从 0 到 49 计数。
感谢您对此的任何帮助!
【问题讨论】:
-
提示:
i和count在任何时候都具有完全相同的值,因此没有必要拥有两个变量。
标签: c struct operating-system pipe