gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:20 24 4
gpt4 key购买 nike

我正在学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com