0
我想了解管道和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
设为“Hello world”?为什么?我的猜测是它是随机的,因为子进程和父进程同时运行。这是真的 ?
好的如果'fork'被调用时'pipe'不是空的? – dimitris93
然后,读取将返回(最多取决于缓冲区大小)管道中的内容,并且不会等待更多内容。 – Ekleog
你怎么知道'read'会在'write'之前发生。父进程和子进程同时执行正确?那么,读取结果是不是随机的? – dimitris93