我正在尝试理解管道和 C 中 fork 的使用。 下面是一个调用 fork()
然后:
- 子进程:读取
pipe
并将内容打印到控制台。 -
父进程:在
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
,它们被视为文件,以便子进程和父进程可以通信。(这是对的吗?现在,由于管道同时来自父级和子级,那么子级会读取空pipe
吗?还是pipe
是"你好世界"?为什么呢?我的猜测是它是随机的,因为子进程和父进程同时运行。这是真的吗?
根据man 7 pipe
,"如果一个进程试图从空管道中读取,那么read(2)将阻塞,直到数据可用。
因此,如果read
发生在write
之前,它将等到write
完成。
相反,如果read
发生在write
之后,很明显它会返回消息。
这些情况中至少有一种必须是真的,因为,根据man 7 pipe
,"POSIX.1-2001 说小于 PIPE_BUF 字节的 write(2) 必须是原子的",PIPE_BUF
通常足够大,可以容纳比"Hello World"多得多的东西。
因此,read
将返回"你好世界"。