Linux管道:函数读写错误的文件描述符

时间:2016-04-17 10:24:16

标签: c linux pipe

我正在学习C中的管道,我的代码有问题:

我的程序在父进程和子进程之间创建子进程和管道。我正在尝试通过管道从父级发送一个简单的字符串。但出于某种原因,我收到函数的错误消息:

“读错误:文件描述符错误”

“写入错误:错误的文件描述符”

我不知道,问题出在哪里,我刚刚开始学习C中的管道。

这是我的代码:

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

int err( const char* what )//function that writes errors
{
    perror( what );
    exit( -1 );
}

int main()
{
    int fdes[2]; //File descriptors for pipe
    pid_t pid;
    char string[20] = "Hello World\n";//string that I want to send to childs process

    int p = pipe( fdes ); //Creating pipe
    if( p < 0 )
        err( "pipe error\n");

    pid = fork(); //Creating process
    if( pid < 0 )
        err( "fork error\n" );

    if( pid == 0 ) //child
    {
        p = close( fdes[0] ); //Closing unused "write" end of pipe for child
        if( p < 0 )
            err( "close error\n" );

        char str[20]; //I save the message from parent in this string
        int p;
        p = read( fdes[1], str, strlen(str) );// Trying to receive the message and save it in str[]
        if( p < 0 )
            err( "read error\n" );

        printf( "Child received: %s\n", str );
    }
    else //parent
    {
        p = close( fdes[1] ); //Closing unused "read" end of pipe for parent
        if( p<0 )
            err( "close error\n");

        p = write( fdes[0], string, strlen( string ) ); //Trying to send the message to child process
        if( p < 0 )
            err( "write error\n" );

        printf( "Parent sent: %s\n", string );


    }
    return 0;
}

2 个答案:

答案 0 :(得分:2)

您正在读写错误的文件描述符。来自pipe man page

  

pipefd [0]指管道的读取端。 pipefd [1]指的是   写下管道的末端。

答案 1 :(得分:1)

如果read(2)不是有效的文件描述符或未打开以供阅读 ”,则

EBADF会返回fd;同样对于write(2),如果描述符未打开以供写入,则会得到EBADF

函数int pipe2(int pipefd[2], int flags);返回2个文件描述符,以便

  
      
  • pipefd[0]指的是管道的读取端。
  •   
  • pipefd[1]指的是管道的写端。
  •   

考虑数组中与STDIN_FILENOSTDOUT_FILENO对应的文件描述符。您从{strong> 0 (read)和STDIN_FILENO 1 (如writeSTDOUT_FILENO