Read Write 管道行为不当
Read Write misbehaving with pipes
我有一段标准代码,它拒绝 运行 正确。读取总是 returns 零。 write 调用似乎卡住了,永远不会 returns。我曾尝试更改 parent 和 child 的顺序,但似乎不起作用。我不知道出了什么问题。也许是一个错误?帮助将不胜感激。
#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;
}
您在创建管道之前fork
ing ,所以您确实在创建两个管道(四个文件描述符).
因此,两个进程之一中的 fd[READ_END]
无论如何与另一个进程中的 fd[WRITE_END]
无关。
它帮助我 运行 system("ls -l /proc/$$/fd/")
在每个过程中查看管道是如何工作的。
我有一段标准代码,它拒绝 运行 正确。读取总是 returns 零。 write 调用似乎卡住了,永远不会 returns。我曾尝试更改 parent 和 child 的顺序,但似乎不起作用。我不知道出了什么问题。也许是一个错误?帮助将不胜感激。
#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;
}
您在创建管道之前fork
ing ,所以您确实在创建两个管道(四个文件描述符).
因此,两个进程之一中的 fd[READ_END]
无论如何与另一个进程中的 fd[WRITE_END]
无关。
它帮助我 运行 system("ls -l /proc/$$/fd/")
在每个过程中查看管道是如何工作的。