【发布时间】:2018-06-01 14:03:53
【问题描述】:
我从手册页了解到的是 vfork() 子进程使用与父进程相同的资源。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = vfork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
据我了解
close(fd[0]); // In child
write(fd[1], string, (strlen(string)+1));
当我们关闭管道读取端 fd[0] 时,子进程中的上述代码行应该会导致 error no 13 SIGPIPE。但这并没有发生
输入输出是
Received string: Hello, world!
谁能解释一下原因?
【问题讨论】:
-
您在这里问了基本相同的问题:stackoverflow.com/questions/47827680/…。除了 vfork()/exec() 之外不要做任何事情。