管道和FIFO
- 管道(pipe)
管道在Unix及Linux进程间通信是最基础的,很容易理解。管道就像一个自来水管,一端注入水,一端放出水,水只能在一个方向上流动,而不能双向流动。管道是典型的单向通信,即计算机网络中所说的“半双工”。管道又名匿名管道,所以只能用在具有公共祖先的进程之间使用,通常使用在父子进程之间通信。通常是父进程创建一个管道,然后fork一个子进程,此后父子进程共享这个管道进行通信。
管道由pipe函数创建,函数原型如下:
#include<unistd.h>
int pipe(int fd[2]); 成功返回0,否则返回-1;参数fd返回两个文件描述符,fd[0]为读,fd[1]为写,fd[1]的输入是fd[0]的输出。即fd[0]对应读端,fd[1]对应写端。
举例说明一下管道的用法:模拟client-server通信过程,父进程模拟client,子进程模拟server。server向client发送一个字符串,client接收到输出到屏幕。
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <sys/types.h> 5 #include <errno.h> 6 #include <string.h> 7 8 int main() 9 { 10 int fd[2]; 11 pid_t childpid; 12 char buf[100]; 13 14 memset(buf,0,100); 15 //创建一个管道 16 if(pipe(fd) == -1) 17 { 18 perror("pipe() error"); 19 exit(-1); 20 } 21 //创建一个子进程 22 childpid = fork(); 23 if(childpid == 0) 24 { 25 printf("server input a message : "); 26 scanf("%s",buf); 27 //关闭读端 28 close(fd[0]); 29 write(fd[1],buf,strlen(buf)); 30 exit(0); 31 } 32 if(childpid == -1) 33 { 34 perror("fork() error"); 35 exit(-1); 36 } 37 //父进程关闭写端 38 close(fd[1]); 39 read(fd[0],buf,100); 40 printf("client read a message: %s\n",buf); 41 waitpid(childpid,NULL,0); 42 return 0; 43 } 复制代码
时间: 2025-01-14 14:31:54