进程间通信(IPC)是指在不同进程之间传递信息。linux的进程通信方式有管道,消息队列,信号量,共享内存,套接口等方式,下面一一整理。
首先是管道(PIPE),管道是Unix系统IPC最古老的方式,所有的Unix系统都提供这种通信机制。它的优点在于简单易用,缺点在于有限制,详细见下面几点:
- 只能用于父子进程或兄弟进程之间通信
- 大多数系统中都是半双工的,数据信息只能单向流动,如果需要双向通信则需要建立两个管道
- 传输的是无格式字节流,需要双方约定格式
- 管道缓冲区是有限的,等等
首先来看父子进程之间通信的例子。
- #include<stdio.h>
- #include<limits.h>
- #include<sys/types.h>
- #include<string.h>
- #include<stdlib.h>
-
- #define BUFSIZE PIPE_BUF //管道默认一次性读取的数据长度
-
- void err_quit(char *err) {
- printf("%s\n",err);
- exit(-1);
- }
-
- int main()
- {
- int fd[2];
- char buf[BUFSIZE] = "hello my son";
- pid_t pid;
-
- if (pipe(fd) < 0) {
- err_quit("pipe error");
- }
- if ((pid = fork()) < 0) {
- err_quit("fork error");
- }
- else if(pid > 0) { //父进程
- close(fd[0]);
- write(fd[1], buf, strlen(buf));
- }
- else {
- close(fd[1]);
- int len = read(fd[0], buf, BUFSIZE);
- if (len < 0) {
- err_quit("read error");
- }
- printf("Get : %s\n",buf);
- }
- return 0;
- }
接下来是兄弟进程之间通信的例子。
- #include<stdio.h>
- #include<limits.h>
- #include<sys/types.h>
- #include<string.h>
- #include<stdlib.h>
-
- #define BUFSIZE PIPE_BUF //管道默认一次性读取的数据长度
-
- void err_quit(char *err) {
- printf("%s\n",err);
- exit(-1);
- }
-
- int main()
- {
- int fd[2];
- char buf[BUFSIZE] = "hello my brother";
- pid_t pid;
-
- if (pipe(fd) < 0) {
- err_quit("pipe error");
- }
- if ((pid = fork()) < 0) {
- err_quit("fork error");
- }
- else if(pid > 0) { //父进程
-
- if ((pid = fork()) < 0) {
- err_quit("fork error");
- }
- else if (pid > 0) { //父进程
-
- }
- else {
- close(fd[0]);
- write(fd[1], buf, strlen(buf));
- }
- }
- else {
- close(fd[1]);
- int len = read(fd[0], buf, BUFSIZE);
- if (len < 0) {
- err_quit("read error");
- }
- printf("Get : %s\n",buf);
- }
- return 0;
- }
代码都很简单,只是需要记住在创建新进程后记得分别关闭读写描述符。如果想让子进程给父进程传递数据,则关闭父进程的写描述符和子进程的读描述符即可。利用管道可以做简单的进程同步工作,因为读端会一直阻塞到写端发出数据后再运行后面的代码,可以利用这个特点保证让指定的进程先运行。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。