如何使用两个管道在子/父之间发送消息

时间:2016-04-13 02:18:50

标签: c++

使用管道在父母和孩子之间发送消息

我无法弄清楚我的代码上的错误

这是我的代码:

df1 <- structure(list(Source_File = c("xxx_00001.csv", "xxx_00001.csv", 
"xxx_00001.csv", "xxx_00001.csv", "xxx_00001.csv", "xxx_00002.csv", 
"xxx_00002.csv", "xxx_00002.csv", "xxx_00002.csv", "xxx_00003.csv", 
"xxx_00003.csv", "xxx_00003.csv", "xxx_00003.csv", "xxx_00003.csv", 
"xxx_00003.csv")), .Names = "Source_File", class = "data.frame", 
row.names = c(NA, -15L))

2 个答案:

答案 0 :(得分:0)

此代码似乎非常混乱。

子进程close(f_des[1]); - s,然后稍后尝试写入它。

父进程close(f_des[0]); - s。它不会关闭它,而是关闭两次。然后它试图从中读取。关闭一次文件后读取文件已经很难了;你可以放心,在完成两次关闭后,你绝对没有成功的机会。

您可能需要坐下来,在一张纸上绘制一张图表,其中包括所有四个文件描述符,两对管道,以及每个管道在每个过程中应该做些什么,父母和孩子;以及在每个过程中需要关闭哪一个。

答案 1 :(得分:0)

我尝试修改此程序,以便孩子在收到消息后更改其大小写并将消息(通过管道)返回给父级,然后显示它。

#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <string.h>
using namespace std;
int
main(int argc, char *argv[ ]) {
    int            f_des[2];
    static char    message[5];
    if (argc != 2) {
        cerr << "Usage: " << *argv << " message\n";
        return 1;
    }
    if (pipe(f_des) == -1) {             // generate the pipe
        perror("Pipe");     return 2;
    }
    switch (fork( )) {
        case -1:
            perror("Fork");     return 3;
        case 0:                              // In the child
            close(f_des[1]);
            if (read(f_des[0], message, BUFSIZ) != -1) {
                cout << "Message received by child: [" << message
                << "]" << endl;
                cout.flush();
            } else {
                perror("Read");    return 4;
            }
            break;
        default:                             // In the Parent
            close(f_des[0]);
            if (write(f_des[1], argv[1], strlen(argv[1])) != -1) {
                cout << "Message sent by parent   : [" <<
                argv[1] << "]" << endl;
                cout.flush();
            } else {
                perror("Write");   return 5;
            }
    }
    return 0;
}