2017-02-20 68 views
0

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

#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; 
} 

而且还有我的 “chield” 计划:

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

程控输出:

呼应< < /家庭/ PI/1

林发现write()返回-1。 但我不知道为什么?

回答

0

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

你写管道的读出端。

除此之外,您的应用程序受到死锁威胁。如果你试图编写太多以至于管道缓冲区填满了,那么孩子生成的管道缓冲区填满了那么多的数据呢?然后这两个进程都在等待另一个进程清空缓冲区,但是每个进程都被阻塞在write

+0

是的,现在写入似乎很好。但现在我的编录在read()循环中。看起来像我的领域不抓住任何标准输入,也不发送任何标准输出。 –

相关问题