【发布时间】:2015-06-03 14:33:15
【问题描述】:
我有一段标准的代码拒绝正确运行。读取始终返回零。 write 调用似乎卡住了,永远不会返回。我试过改变父母和孩子的顺序,但似乎没有用。我不知道出了什么问题。也许是一个错误??帮助将不胜感激。
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define READ_END 0
#define WRITE_END 1
int main()
{
int pid;//,bytes;
pid=fork();
char buffer[100];
char msg[]="Hello";
//const char *msg2="Hi";
int fd[2];
//int p2[2];
/* create the pipe */
if (pipe(fd) == -1)
{
fprintf(stderr,"Pipe failed");
return 1;
}
if (pid < 0)
{ /* error occurred */
fprintf(stderr, "Fork Failed");
return 1;
}
if (pid > 0)
{ /* parent process */
/* close the unused end of the pipe */
close(fd[WRITE_END]);
/* read from the pipe */
int bytesRead = read(fd[READ_END], buffer, 100);
printf("read %d",bytesRead);
/* close the write end of the pipe */
close(fd[READ_END]);
wait(NULL);
}
else
{
/* child process */
/* close the unused end of the pipe */
close(fd[READ_END]);
/* write to the pipe */
int bytesWritten = write(fd[WRITE_END], msg, strlen(msg)+1);
printf("%d",bytesWritten);
/* close the write end of the pipe */
close(fd[WRITE_END]);
}
return 0;
}
【问题讨论】:
-
你需要
pipe()之前你fork()。
标签: c pipe fork ubuntu-12.04