无名管道(pipe)使用实例
无名管道(pipe)的创建实例,一下程序在子进程中写入数据,在父进程中读取数据
View Code
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 int main() 6 { 7 pid_t pid; 8 int pipedes[2]; 9 char s[14] = "test message!"; 10 char d[14] = {0}; 11 12 if(pipe(pipedes) == -1)//创建管道 13 { 14 perror("pipe"); 15 exit(1); 16 } 17 18 if((pid = fork()) == -1)//创建新进程 19 { 20 perror("fork"); 21 exit(1); 22 } 23 else if(pid == 0)//子进程 24 { 25 printf("write data to the pipe\n"); 26 if(write(pipedes[1], s, 14) == -1)//写数据到管道 27 { 28 perror("write"); 29 exit(1); 30 } 31 else 32 { 33 printf("the written data is %s\n", s); 34 } 35 } 36 else if(pid > 0)//父进程 37 { 38 sleep(2);//休眠2秒钟,让子进程先运行 39 printf("read data from the pipe\n"); 40 if(read(pipedes[0], d, 14) == -1)//读取管道数据 41 { 42 perror("read"); 43 exit(1); 44 } 45 printf("data from pipe is %s\n", d); 46 } 47 48 return 0; 49 }