这里先看两个例子:
1) 源码如下:
1 #include <sys/types.h> 2 3 #include <stdio.h> 4 5 #include <stdlib.h> 6 7 #include <unistd.h> 8 9 #include <errno.h> 10 11 12 13 int main(int argc, char *argv[]) 14 15 { 16 17 pid_t pid; 18 19 20 21 fprintf (stderr, "this is stderr string! "); 22 23 printf ("this is stdout string! "); 24 25 26 27 if ((pid = fork()) == 0) 28 29 { 30 31 32 33 } 34 35 else if (pid > 0) 36 37 { 38 39 40 41 } 42 43 else 44 45 { 46 47 fprintf (stderr, "fork error! errno: %d errstr: %s ", errno, strerror(errno)); 48 49 } 50 51 52 53 exit(0); 54 55 }
运行:
问:这里printf ("this is stdout string!
");为什么会在文件中打印两句出来?而在不重定向的情况下只打印一次;
2) 这是一个进程间的pipe通信,代码如下:
1 // main_process.c 2 3 #include <sys/types.h> 4 5 #include <stdio.h> 6 7 #include <stdlib.h> 8 9 #include <unistd.h> 10 11 12 13 int main(int argc, char *argv[]) 14 15 { 16 17 int pipe_fd[2]; 18 19 pid_t pid; 20 21 char pipe_buf[1024]; 22 23 int ret; 24 25 26 27 if (pipe(pipe_fd) < 0) 28 29 fprintf(stderr, "pipe failed! "); 30 31 32 33 if ((pid = fork()) == 0) /* child */ 34 35 { 36 37 close(pipe_fd[0]); 38 39 dup2(pipe_fd[1], STDOUT_FILENO); 40 41 close(pipe_fd[1]); 42 43 if (execl("./child_process", "./child_process", NULL) == -1) 44 45 fprintf (stderr, "execl faild! "); 46 47 exit(0); 48 49 } 50 51 else if (pid > 0) /* parent */ 52 53 { 54 55 close(pipe_fd[1]); 56 57 while ((ret = read(pipe_fd[0], pipe_buf, sizeof(pipe_buf) - 1)) > 0) 58 59 { 60 61 pipe_buf[ret] = '