进程通信——无名管道
linux进程间通信方式有很多种,包括管道通信、消息队列、共享内存、信号量、套接字等。管道通信分为有名管道和无名管道,其中最简单的当属无名管道。无名管道只能用于父子进程间的通信,无法在网络中使用。
我理解的管道实质上就是一个共享文件,其中一个进程负责向该管道写入数据,另一个进程就可以按照先入先出的原则从中读取数据,但是该共享文件的使用是互斥的,即同一个时刻只能进行读或者写里面的其中一个动作,不能兼而有之。共享文件的大小也是事先确定的,如果超出大小就会发生溢出。
在解释无名管道之前,先回顾一下创建子进程的方法,在linux下,创建子进程的系统调用原形为:int fork();返回值是生成子进程的进程号,如果返回-1则意味着创建失败。
创建管道的方法:int pipe(int file_descriptor[2]);
读取数据方法:int read(int pipe_fd,char *buffer,size_t len);
写入数据的方法:int write(int pipe_fd,char *buffer,size_t len);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | #include #include #define INPUT 0 #define OUTPUT 1 int main() { int file_descriptors[2]; /*定义子进程号 */ pid_t pid; char buf[BUFFER_LEN]; int returned_count; /*创建无名管道*/ pipe(file_descriptors); /*创建子进程*/ if ((pid = fork()) == - 1) { printf("Error in fork\n"); exit(1); } /*执行子进程*/ if (pid == 0) { printf("in the spawned (child) process...\n"); /*子进程向父进程写数据,关闭管道的读端*/ close(file_descriptors[INPUT]); write(file_descriptors[OUTPUT], "test data", strlen("test data")); exit(0); } else { /*执行父进程*/ printf("in the spawning (parent) process...\n"); /*父进程从管道读取子进程写的数据,关闭管道的写端*/ close(file_descriptors[OUTPUT]); returned_count = read(file_descriptors[INPUT], buf, sizeof(buf)); printf("%d bytes of data received from spawned process: %s\n", returned_count, buf); } } |
Tell us which tools, resources, menotrs, etc. ,
[回复]