C 管道 write/read 优先级
C pipes write/read priority
我正在尝试了解管道和 fork 在 C 中的使用。下面是一个代码示例,它调用 fork()
然后:
- Child 进程:读取
pipe
并将内容打印到控制台。
Parent过程:写入pipe
"hello world".
int main(void)
{
pid_t pid;
int mypipe[2];
/* Create the pipe. */
if (pipe(mypipe))
{
fprintf(stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
/* Create the child process. */
pid = fork();
if (pid == (pid_t)0)
{
/* This is the child process.
Close other end first. */
close(mypipe[1]);
read_from_pipe(mypipe[0]);//read pipe and print the result to console
return EXIT_SUCCESS;
}
else if (pid < (pid_t)0)
{
/* The fork failed. */
fprintf(stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
/* This is the parent process.
Close other end first. */
close(mypipe[0]);
write_to_pipe(mypipe[1]);//write "hello world" to the pipe
return EXIT_SUCCESS;
}
}
我的理解是,我们使用pipes
,把它们当作文件,这样child进程和parent进程就可以通信了。 (这是正确的吗?)现在,由于 parent 和 child 都在使用管道,child 会读取一个空的 pipe
吗?或者 pipe
会是 "Hello world" 吗?为什么?我的猜测是它是随机的,因为 child 和 parent 同时处理 运行。这是真的 ?
根据man 7 pipe
,"If a process attempts to read from an empty pipe, then read(2) will block until data is available."。
因此,如果 read
发生在 write
之前,它将等到 write
完成。
反过来,如果 read
出现在 write
之后,很明显它会 return 消息。
并且这些情况中至少有一个必须是真实的,因为,仍然根据 man 7 pipe
、"POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic",而 PIPE_BUF
通常大到足以容纳比 "Hello World".
因此 read
将 return "Hello world"。
我正在尝试了解管道和 fork 在 C 中的使用。下面是一个代码示例,它调用 fork()
然后:
- Child 进程:读取
pipe
并将内容打印到控制台。 Parent过程:写入
pipe
"hello world".int main(void) { pid_t pid; int mypipe[2]; /* Create the pipe. */ if (pipe(mypipe)) { fprintf(stderr, "Pipe failed.\n"); return EXIT_FAILURE; } /* Create the child process. */ pid = fork(); if (pid == (pid_t)0) { /* This is the child process. Close other end first. */ close(mypipe[1]); read_from_pipe(mypipe[0]);//read pipe and print the result to console return EXIT_SUCCESS; } else if (pid < (pid_t)0) { /* The fork failed. */ fprintf(stderr, "Fork failed.\n"); return EXIT_FAILURE; } else { /* This is the parent process. Close other end first. */ close(mypipe[0]); write_to_pipe(mypipe[1]);//write "hello world" to the pipe return EXIT_SUCCESS; } }
我的理解是,我们使用pipes
,把它们当作文件,这样child进程和parent进程就可以通信了。 (这是正确的吗?)现在,由于 parent 和 child 都在使用管道,child 会读取一个空的 pipe
吗?或者 pipe
会是 "Hello world" 吗?为什么?我的猜测是它是随机的,因为 child 和 parent 同时处理 运行。这是真的 ?
根据man 7 pipe
,"If a process attempts to read from an empty pipe, then read(2) will block until data is available."。
因此,如果 read
发生在 write
之前,它将等到 write
完成。
反过来,如果 read
出现在 write
之后,很明显它会 return 消息。
并且这些情况中至少有一个必须是真实的,因为,仍然根据 man 7 pipe
、"POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic",而 PIPE_BUF
通常大到足以容纳比 "Hello World".
因此 read
将 return "Hello world"。