|
REDHAT 8.0
gcc
在学习PIPE的过程中,将以下代码编译,a.out
在终端下执行
$ a.out
输出:
hello world in parent and write to child
end read 42 bytes!
和
$ a.out &
输出:
begin to write 42 bytes...
hello world in parent and write to child
end read 42 bytes!
的运行结果为什么不一样?
- /************************************************************************************************
- * Name : s_pipe1.c
- * Descript : Example14.1 in Advanced Programming in the UNIX Environment
- * Date : 2003-9-29 星期一 29 九月 2003
- * Author : Kicool
- * Key : pipe
- * Function : int pipe(int filedes[2]);
- *************************************************************************************************/
- #include <sys/types.h>
- #include "ourhdr.h"
- int main(void)
- {
- int n, fd[2];
- pid_t pid;
- char line[MAXLINE];
- char buf[] = "hello world in parent and write to child\n";
- n = strlen(buf) +1;
- if (pipe(fd) < 0)
- err_sys("pipe error");
- if ((pid = fork()) < 0)
- err_sys("fork error");
- else if (pid > 0) {
- close(fd[0]);
- printf("\nbegin to write %d bytes...\n", n);
- write(fd[1], buf, n);
- } else {
- close(fd[1]);
- n = read(fd[0], line, MAXLINE);
- write(STDOUT_FILENO, line, n);
- printf("\nend read %d bytes!\n", n);
- }
- exit(0);
- }
复制代码 |
|