我试图理解管道和 C 语言中 fork 的使用。下面是一个调用 fork()
的代码示例,然后:
- 子进程:读取
管道
并将内容打印到控制台。 父进程:在
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; } }
我的理解是,我们使用管道
,把管道当做文件来处理,这样子进程和父进程就可以进行通信了。 (这是正确的吗?)现在,由于父项和子项都在使用管道,子项是否会读取一个空的 pipe
?或者 pipe
会是“Hello world”吗?为什么?我的猜测是它是随机的,因为子进程和父进程同时运行。这是真的 ?
最佳答案
根据 man 7 pipe
,“如果进程试图从空管道读取数据,则 read(2) 将阻塞直到数据可用。”。
因此,如果read
发生在write
之前,它将等到write
完成。
反过来,如果 read
发生在 write
之后,很明显它会返回消息。
并且这些情况中至少有一个必须是真实的,因为,仍然根据 man 7 pipe
,“POSIX.1-2001 表示小于 PIPE_BUF 字节的 write(2)s 必须是atomic”,PIPE_BUF
通常足够大,可以容纳比“Hello World”更多的内容。
所以 read
将返回“Hello world”。
关于C 管道写/读优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29873037/