日期:2014-05-16  浏览次数:20823 次

linux pipe无法write!!!!!
C/C++ code

#include<unistd.h>
#include<sys/types.h>
#include<iostream>
#include<string.h>
int main(int argc,char* argv[])
{
    int command_pipe[2];
    pid_t pid;
    pid = fork();
    char command_string[255];
    if(pipe(command_pipe) < 0)
        std::cerr<<"pipe failed"<<std::endl;
    if(pid<0)
        std::cerr<<"fork failed!"<<std::endl;
    if(pid == 0)
    {
        char ch[255] = {'\0'};
        close(command_pipe[1]);
        int n=read(command_pipe[0],ch,255);
        std::cout<<"child read:"<<n<<std::endl;
        std::cout<<ch<<std::endl;

    }
    else
        if(pid >0)
        {
            close(command_pipe[0]);
            char m[255];
            strcpy(m,"111");
            if(-1!= write(command_pipe[1],m,4))
                std::cout<<"write success"<<std::endl;
                        else
                                 std::cout<<"write fail"<<std::endl;
            close(command_pipe[1]);
        }
    return 0;
}






上面代码无法实现管道通信。
输出:
child read :0

因为write句子写了if else 所以 write success和write fail至少有一个会输出,但实际上二者都未输出
请问是为什么呢?
如何解决?谢谢

------解决方案--------------------
你的代码父子进程各自创建了各自的pipe.

然后子进程关闭自己管道的写, 进行读是可行的.
但是父进程会出错,因为关闭了读,写管道是不行的哦,man write看一下帮助把.

错误就是fork和pipe配合的问题, 应该先pipe, 然后fork, 这样子进程就继承了pipe的fd