进程间通信(IPC):管道,信号量,共享内存,消息队列,套接字
1.管道
管道可以用来在两个进程之间传递数据,如:ps -ef | grep "bash",其中'|'就是管道,其作用就是将ps命令的结果写入管道文件,然后grep再从管道中读取出该数据进行过滤。
1.1 有名管道
有名管道可以在任意两个进程之间通信
有名进程的创建:
命令创建:mkfifo FIFO
系统调用创建
# include <sys/types.h> # include <sys/stat.h> int mkfifo (const char*filename,mode_t mode); //filename是管道名 mode是创建的文件访问权限
管道本身不占用空间,它只是在内存中开辟空间,管道中的文件写到内存中
1.2 无名管道
无名管道主要应用于父子进程间的通信
无名管道创建:
# include <unistd.h> int pipe(int fds[2]); //pipe()成功返回0,失败返回-1 //fds[0]是管道读端描述符 //fds[1]是管道写端的描述符
//无名管道代码演示 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <string.h> int main() { int fd[2]; int res = pipe(fd); assert( res != -1 ); pid_t pid = fork(); assert( pid != -1 ); if( pid == 0 ) { char buff[128] = {0}; read(fd[0], buff, 127); printf("child read: %s\n", buff); } else { write(fd[1], "hello", 5); } close(fd[0]); close(fd[1]); exit(0); }
1.3 管道的特点
1.无论有名还是无名写入管道的数据都存在内存中
2.管道是一种半双工的通信方式(通信方式有单工、半双工、全双工)
3.有名和无名管道的区别:有名可以在任意进程间使用,而无名主要在父子进程间
管道的实现
06-10
8406

04-15
8177
