从管道写入和读取时,我得到了不寻常的结果。运行时错误程序由signal: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;
}
有关如何解决此运行时错误的任何建议吗?
答案 0 :(得分:0)
您需要在分叉子进程之前打开管道。否则,您的流程不会与同一个管道进行通信。
因此,将管道创建代码移到fork()调用之上,如下所示:
videomixer