簡體   English   中英

Linux 管道:讀取和寫入函數中的文件描述符錯誤

[英]Linux pipe: Bad file descriptor in functions read and write

我正在學習 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;
}

您正在讀取和寫入錯誤的文件描述符。 管道手冊頁

pipefd[0] 指的是管道的讀取端。 pipefd[1] 指的是管道的寫端。

read(2)如果fd不是有效的文件描述符或未打開讀取”,則返回EBADF 同樣,對於write(2) ,如果描述符未打開寫入,您將獲得EBADF


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

  • pipefd[0]指的是管道的讀取端。
  • pipefd[1]指的是管道的寫端。

想想對應於STDIN_FILENOSTDOUT_FILENO的數組中的文件描述符。 您將從0 read (如STDIN_FILENO ),然后write 1 (如STDOUT_FILENO )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM