如何使用管道通过文件在 parent 和 child 之间共享数据?

How to share data between parent and child via files using pipes?

我知道 parent 和 child 可以使用共享内存或通过套接字进行通信。我正在尝试让他们使用管道相互通信。

我首先使用 fork 创建了一个 child,我最终希望 child 读取来自 stdout 的消息,该消息将由 parent 输出,但我无法为此,我试图让他们通过临时文件进行通信。

fork 之后,我使用 dup2 将此文件设置为 child 的 input-fd 和 parent 的 output-fd。然后使用 sleep 我确保 child 在 parent 输出后读取。

#include<bits/stdc++.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

int main(int argc, char**  argv){
    if(argc<2){
        printf("Usage: %s <string>\n", argv[0]);
        return 0;
    }
    int raw_desc = open("/tmp/raw.txt",O_RDWR);
    if(raw_desc<0){
        FILE* fptr = fopen("/tmp/raw.txt", "a+");
        raw_desc = open("/tmp/raw.txt",O_RDWR);
    }
    int f=fork();
    if(f==0){
        dup2(raw_desc, 0);
        sleep(3);
        string s;
        cin>>s;
        cout<<"Child got : "<<s<<endl;
    }else{
        dup2(raw_desc, 1);
        sleep(1);
        cout<<std::string(argv[1])<<endl;
        wait(NULL);
    }
    return 0;
}

I first create a child using fork and the I finally want child to read message from stdout which will be outputted by parent, but I was unable to this so I am trying to make them communicate from a temporary file.

使用 pipedup2 很容易实现。也许您需要阅读 manual.

以下是如何使用管道连接 parent 的标准输出和 child 的标准输入的示例。

parent:

int fd[2];
pipe(fd);
int saved_stdout = dup(1); // maybe you will want to save the stdout fd and recover it later
dup2(fd[1], 1); // parent: write to fd[1]
// do writing
dup2(saved_stdout, 1); // restore stdout

child:

int saved_stdin = dup(0); 
dup2(fd[0], 0); // child: read from fd[0]
// do reading
dup2(saved_stdin, 0); // restore stdin