【问题标题】:read and write with the same process using two different pipes c++使用两个不同的管道c ++使用相同的进程读取和写入
【发布时间】:2023-03-10 18:10:02
【问题描述】:

我正在尝试创建一个调用某个程序或进程的子进程。父级通过两个管道从子级写入和读取一些数据。我的代码编译并运行,但输入中没有文本。我究竟做错了什么?我是不是没有正确关闭管道、写入管道或正确输出数据?

#include <iostream>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>  
#include <unistd.h>
#include <string.h>  

int main(){
   int pipedes1[2],pipedes2[2];
   char buff[256];
   string text = "Hello";
   pid_t pid;
   pipe(pipedes1);
   pipe(pipedes2);
   pid = fork();
   if(pid > 0){

       close(pipedes1[1]);
       close(pipedes2[0]);

       dup2(pipedes2[1], STDOUT_FILENO);
       dup2(pipedes1[0], STDIN_FILENO);

       execve("/home/pi/Test", NULL, NULL);

   } else {

       close(pipedes1[1]);
       close(pipedes2[1]);

       write(pipedes1[0], text.c_str(), text.length());
       while((len = read(pipedes2[0], buff, 256)) != 0){
            cout << buff << endl;
       }
       close(pipedes2[0]);
       close(pipedes1[0]);
   }
   return 0;
}

还有我的“孩子”程序:

int main(){
    string str;
    cin >> str;
    str = "echo " + str + " >> /home/pi/1";
    cout << str << endl;
    return 0;
}

程序的输出:

回声

我发现一个问题 write() 返回 -1。 但是不知道为什么?

【问题讨论】:

    标签: c++ subprocess pipe fork


    【解决方案1】:

    write(pipedes1[0], text.c_str(), text.length());

    您正在写入管道的读取端。

    除此之外,您的应用程序会受到死锁的威胁。如果你试图写太多以至于管道缓冲区填满,而子进程产生的数据太多以至于它的管道缓冲区也填满了怎么办?然后两个进程都在等待另一个进程耗尽缓冲区,但它们都被 write 阻塞了!

    【讨论】:

    • 是的,现在写似乎没问题。但是现在我的程序陷入了 read() 循环。似乎我的孩子没有捕获任何标准输入,也没有发送任何标准输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多