c - Linux 管道 : Bad file descriptor in functions read and write

标签 c linux pipe

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

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

"read error: Bad file descriptor"
"write error: bad file descriptor"

我不知道问题出在哪里,我刚刚开始学习 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;
}

最佳答案

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

pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe.

关于c - Linux 管道 : Bad file descriptor in functions read and write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36675318/

相关文章:

linux - 如何缩小 UNIX/LINUX 下进程列表输出的范围

c - beej导流管实例讲解

c - 从管道读取时循环未完成

c - 如果我们同时初始化 union 体的所有成员会发生什么?

c - 不确定如何修复我收到的警告

linux - 如何打印两个文件之间的差异

Linux watch 命令 "no such file or directory"

c# - NamedPipeClientStream 在应用程序服务中不起作用

c - 没有括号的 for 循环的绝对范围是什么?

C++指针解释