linux 中进程通信实现
通信方式:管道 消息队列 共享内存 信号量 套接口
1.管道
包括无名管道和有名管道,前者用于父子进程的通信,后者用于运行于同一台
机器上的任意两个进程间的通信。
1)无名管道
创建:#include<unistd.h>
int pipe(int pipefd[2])
参数:pipefd[0]为读而打开,pipefd[1]为写而打开。
例:
#include<unistd.h> #include<sys/types.h> #include<stdio.h> #include<stdlib.h> #include<string.h> void main() { int pidfd[2]; char buf[256]; int fd=pipe(pidfd); if(fd<0) { printf("pipe error "); exit(-1); } pid_t pid; if((pid=fork())==-1) { printf("error fork "); exit(-1); } if(pid == 0) { printf("I am child process! "); close(pidfd[0]); write(pidfd[1],"hello ipc",strlen("hello ipc")+1); exit(0); } else { printf("I am father process! "); close(pidfd[1]); read(pidfd[0],buf,sizeof(buf)); printf("%s ",buf); } }
说明:关闭打开管道,只是相对于自己的进程号来看的。
但是系统创建的管道,由于字节是依赖于系统定义的,使用流管道,就会突破系统
的限制。
讲解函数:
例:
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<fcntl.h> #define BUFSIZE 1024 int main() { FILE *fp; char *cmd = "ps -ef"; char buf[BUFSIZE]; buf[BUFSIZE]='