【问题标题】:Read and write from/to piped stdin,stdout从/向管道标准输入、标准输出读取和写入
【发布时间】:2021-03-01 08:40:21
【问题描述】:

我需要在 2 个不同的进程之间传递信息,我尝试使用管道来做到这一点。由于我从未使用过它们,我试图从基础开始。但是,我似乎无法从子进程中读取信息并将它们写回。

我有以下代码:

int main()
{
int in,out;

popen2("./Reader/reader",&in,&out);
int result = write(in, "hello", sizeof("hello"));
char out_arr[100];

result = read(out, out_arr, sizeof("Received"));
fprintf( stderr, "%s\n", out_arr);

return 0;
}

其中popen2如下:

#define READ 0
#define WRITE 1

pid_t
popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;

if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
    return -1;

pid = fork();

if (pid < 0)
    return pid;
else if (pid == 0)
{

    close(p_stdin[WRITE]);
    dup2(p_stdin[READ], READ);
    close(p_stdout[READ]);
    dup2(p_stdout[WRITE], WRITE);

    execl("/bin/bash", "bash", "-c", command, NULL);
    perror("execl");

    exit(1);
}

if (infp == NULL)
    close(p_stdin[WRITE]);
    else
    {

    *infp = p_stdin[WRITE];
    }

if (outfp == NULL)
    close(p_stdout[READ]);
else

{

    *outfp = p_stdout[READ];
}

return pid;
}

这会打开一个子进程。如何从子进程读取我在主进程中写入管道的“你好”?如何写回主进程?

目前这似乎不起作用:

int main()
{

std::string input;
while(std::cin>>input)
{
    std::cout<<"Received";
}

return 0;
}

【问题讨论】:

    标签: c++ process pipe stdout stdin


    【解决方案1】:

    已解决

    我错过了发送的字符数组末尾的\n\r,以便从子进程中变为红色。

    int main()
    {
    int in,out;
    
    popen2("./Reader/reader",&in,&out);
    int result = write(in, "hello\n\r", sizeof("hello\n\r"));
    char out_arr[100];
    
    result = read(out, out_arr, sizeof("Received"));
    fprintf( stderr, "%s\n", out_arr);
    
    return 0;
    }
    

    【讨论】: