【问题标题】:Broken pipe in Linux(IPC)Linux(IPC)中的管道损坏
【发布时间】:2013-05-29 05:30:44
【问题描述】:

我已经为pipe (linux - IPC) 编写了一个基本示例程序,但我得到了broken pipe 作为输出。

下面是代码:

#include<stdio.h> 

#include<unistd.h> 

#include<sys/types.h> 

#include"iostream" 

using namespace std; 

int main() 
{ 
        int fd[2],n; 
        char arr[50] = "Sample program"; 
        char buf[50] = {0}; 

        if (0 ==  pipe(fd)) 
        { 
                cout<<"Pipe created with fd[0] - "<<fd[0]<<" and fd[1] - "<<fd[1]<<endl; 
        } 

        int pid; 

        if (pid = fork() == -1) 
        { 
                cout<<"Error in FORK"<<endl; 
                exit(1); 
        } 

        if (pid == 0) 
        { 
                cout<<"In Child Process"<<endl; 

                close(fd[0]); 

                write(fd[1], arr, sizeof(arr)); 

                exit(0); 
        } 
    else{ 

                cout<<"In Parent Process"<<endl; 
                close(fd[1]); 

                n = read(fd[0], buf, sizeof(buf)); 

                cout<<"Total bytes read is : "<<n<<endl<<"Buffer is : "<<buf<<endl; 
        }         

        return 0; 
} 

编译:

c++ pipe.cpp -g -o pipe

输出:

使用 fd[0] - 3 和 fd[1] - 4 创建的管道

在子进程中

在子进程中

管道破裂

如何解决这个问题或我在做什么?

【问题讨论】:

    标签: linux ipc pipe broken-pipe


    【解决方案1】:

    你的 if 条件是问题所在。将其更改为 if ((pid = fork()) == -1)

    程序运行良好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2011-03-19
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多