从管道读取时出错

问题描述 投票:0回答:1

在从管道写入和读取时,我得到了不寻常的结果。运行时错误是程序由信号终止:13。我搜索了这个错误,发现这个错误是由于当我从子进程中的管道读取时没有读取器从管道读取。这是我的代码:

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 50
#define READ_END 0
#define WRITE_END 1

int main()
{
int pipe_fd[2];
pid_t pid;
pid = fork();

char message[BUFFER_SIZE] = "Greetings";
char read_message[BUFFER_SIZE];

if( pipe(pipe_fd) == -1)
{
perror("Error in creating the pipe \n");
exit(-1);
}

if(pid==-1)
{
perror("Error in creating the child! \n");
exit(-1);
}

if(pid==0)          // Child process
{
close(pipe_fd[WRITE_END]);
read(pipe_fd[READ_END], read_message , BUFFER_SIZE);
printf("The message read by the child is: %s", read_message);
close(pipe_fd[READ_END]);
}
if(pid>0)           // Parent process
{

close(pipe_fd[READ_END]);   //Closing the read end of the pipe
write(pipe_fd[WRITE_END], message, BUFFER_SIZE);   // Writing to pipe on write_end
close(pipe_fd[WRITE_END]);
}



return 0;
}

有什么建议如何解决这个运行时错误?

linux pipe
1个回答
0
投票

在分叉子进程之前,需要打开管道。否则,您的进程不会与同一个管道通信。

因此,将管道创建代码移到fork()调用之上,如下所示:

if( pipe(pipe_fd) == -1)
{
perror("Error in creating the pipe \n");
exit(-1);
}

pid_t pid;
pid = fork();

char message[BUFFER_SIZE] = "Greetings";
char read_message[BUFFER_SIZE];

if(pid==-1)
{
perror("Error in creating the child! \n");
exit(-1);
}
© www.soinside.com 2019 - 2024. All rights reserved.