1 用户要实现父进程到子进程的数据通道,可以在父进程关闭管道读出一端,
然后相应的子进程关闭管道的输入端。
2 先用pipe()建立管道 然后fork函数创建子进程。父进程向子进程发消息,子进程读消息。
3 实现
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <fcntl.h> 5 #include <limits.h> 6 #include <sys/types.h> 7 #define BUFSZ PIPE_BUF /*PIPE_BUF管道默认一次性读写的数据长度*/ 8 int main ( void ) 9 { 10 int fd[2]; 11 char buf[BUFSZ]; 12 pid_t pid; 13 ssize_t len; 14 if ( (pipe(fd)) < 0 ){ /*创建管道*/ 15 perror ( "failed to pipe" ); 16 exit( 1 ); 17 } 18 if ( (pid = fork()) < 0 ){ /* 创建一个子进程 */ 19 perror ( "failed to fork " ); 20 exit( 1 ); 21 } 22 else if ( pid > 0 ){ 23 close ( fd[0] ); /*父进程中关闭管道的读出端*/ 24 write (fd[1], "hello tian chaoooo! ", 20 ); /*父进程向管道写入数据*/ 25 exit (0); 26 } 27 else { 28 close ( fd[1] ); /*子进程关闭管道的写入端*/ 29 len = read (fd[0], buf, BUFSZ ); /*子进程从管道中读出数据*/ 30 if ( len < 0 ){ 31 perror ( "process failed when read a pipe " ); 32 exit( 1 ); 33 } 34 else 35 write(STDOUT_FILENO, buf, len); /*输出到标准输出*/ 36 exit(0); 37 } 38 }
4 截图