[英]pipe, when parent close fd[1], what the child will get from fd[0]?
#define STACK_SIZE (1024 * 1024)
static char container_stack[STACK_SIZE];
char* const container_args[] = {
"/bin/bash",
NULL
};
int pipefd[2];
...
int container_main(void* arg)
{
...
char ch;
close(pipefd[1]);
read(pipefd[0], &ch, 1);
printf("Get EOF [%d] from parent!\n", ch);
...
execv(container_args[0], container_args);
printf("Something's wrong!\n");
return 1;
}
int main()
{
...
pipe(pipefd);
printf("Parent [%5d] - start a container!\n", getpid());
int container_pid = clone(container_main, container_stack+STACK_SIZE,
CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWUSER | SIGCHLD, NULL);
...
close(pipefd[1]);
...
return 0;
}
So, in parent process, I close(pipefd[1]);
因此,在父进程中,我
close(pipefd[1]);
, then, if I read from read(pipefd[0], &ch, 1);
,那么,如果我从
read(pipefd[0], &ch, 1);
in child, I'll continue jobs in child process. 在孩子中,我将继续在孩子过程中工作。 That make sense.
有道理。
But when I printed the value of ch
, it's 0
, I think it should be -1
, which means EOF. 但是当我打印
ch
的值时,它是0
,我认为应该是-1
,这意味着EOF。
So can anyone tell me why I read 0
from fd[0] in child instead of EOF? 那么谁能告诉我为什么我从child的fd [0]中读取
0
而不是EOF?
read()
returns 0
on EOF
... it returns -1
for errors, so if the other end of the pipe is closed, you expect read to return 0
and not modify ch at all. read()
在EOF
上返回0
...对于错误,它返回-1
,因此,如果管道的另一端关闭,则您希望read返回0
而根本不修改ch。
That's my mistake, I expected to print EOF to -1
but read()
have already deal with EOF
and return 0
. 那是我的错误,我希望将EOF打印为
-1
但read()
已经处理了EOF
并返回0
。
Thanks Dmitri & William Pursell 感谢Dmitri和William Pursell
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.