【问题标题】:Pipe a struct from multiple children in C在 C 中管道来自多个子级的结构
【发布时间】: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 计数。

感谢您对此的任何帮助!

【问题讨论】:

  • 提示:icount 在任何时候都具有完全相同的值,因此没有必要拥有两个变量。

标签: c struct operating-system pipe


【解决方案1】:

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

简单的解决方案:将调用移至循环外的pipe

我相信如果写入在一定大小以下,保证是原子的,所以只要结构足够小,这是安全的。

【讨论】:

  • 非常感谢。我的任务现在有效!从字面上看,我所要做的就是将管道移到 for 循环之外,然后我得到了我正在寻找的确切结果。感谢您花时间查看我的代码并帮助我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
相关资源
最近更新 更多