进程间通信的六种方式
IPC的方式通常有管道(Streams)(包括无名管道和命名管道)、消息队列、信号、信号量、共享存储、Socket等。
一、管道-pipe-半双工-父子进程之间
int pipe(int pipefd[2]);
-
特点
1.只能基于亲缘关系的通信。
2.管道中的数据读完就没了。
3.它是半双工的。
4.对它的读写可以使用read、write,它不是普通文件,并不属于其他任何文件系统,并且只存在于内存中。
5.成功返回0,失败返回-1。 -
例子:父进程往管道中写数据,然后子进程读出数据
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
int main()
{
int fd[2];
char buf[128]="linux c";
char readbuf[128]={
'\0'};
int len=strlen(buf);
pipe(fd);
pid_t pid=fork();
if(pid>0){
printf("this is the father!!!\n");
close(fd[0]);
write(fd[1],buf,len);
sleep(3);
}else if(pid==0){
close(fd[1]);
read(fd[0],readbuf,len);
printf("this is child!!!,father date:%s\n",readbuf);
}
return 0;
}
~
二、命名管道—mkfifo—半双工
FIFO,也称为命名管道,它是一种文件类型。
-
特点
1.FIFO可以在无关的进程之间交换数据,与无名管道不同。
2.FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
3.成功返回0,失败返回-1.
4.使用open,read,write,close进行操作。 -
原型
int mkfifo(const char *pathname, mode_t mode);
读端代码,如果open文件以只读打开该进程会阻塞并等待写入数据
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
int main()
{
char readbuf[128]={
'\0'};
if(mkfifo("./file", 0600)==-1){
perror("create fall,why");
exit(0);
}
int fp=open("./file",O_RDONLY);
if(fp==-1){
printf("open fail!\n");
}
read(fp,readbuf,128);
printf("date=%s\n",readbuf);
close(fp);
return 0;
}
写端代码
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
int main()
{
char *writebuf=(char *)malloc(128);
memset(writebuf,'\0',128);
int fp=open("./file",O_WRONLY);
if(fp==-1){
printf("open fail\n");
perror("why");
}
printf("please put date:\n");
scanf("%s",writebuf);
int len=strlen(writebuf);
write(fp,writebuf,len);
close(fp);
return 0;
}
三、消息队列
消息队列,是消息的链接表,存放在内核中,一个消息队列由一个标识符(即队列ID)来标识。
1.特点
- 消息队列是面向记录的,其中的消息具有特定的格式以及特定的优先级。
- 消息队列独立于发送与接收进程。进程终止时,消息队列及其内容并不会被删除。
- 消息队列可以实现消息的随机查询,消息不一定要以先进先出的次序读取,也可以按消息的类型读取。
2.各api
(1)ftok—产生一个ID值
一般写法:ftok(".",123);//参数proj_id随便写
系统建立IPC通讯(消息队列、信号量和共享内存)时必须指定一个ID值。通常情况下,该id值通过ftok函数得到。
失败返回-1,成功返回产生的key值。
key_t ftok(const char *pathname, int proj_id);//
ls -i 显示当前所有文件的索引值
ls -ai 查看当前所有文件以及其索引值
(2)msgget—找到消息队列
失败返回-1并可有perror打印原因,成功返回队列id
int msgget(key_t key, int msgflg);
参数 | 说明 |
---|---|
msgflg | 一般填“ IPC_CTEAT ‘竖线’ 0777 ”(没有队列就创建,以可读可写可执行的方式) |
(3)msgsnd—写入
失败返回-1,成功返回0
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
(4)msgrcv—接收
失败返回-1,成功返回接收到的数据长度
一直阻塞到接收到数据为止
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
参数 | 说明 |
---|---|
msqid | 队列id号 |
msgp | 结构体地址 |
msgsz | 结构体mtext长度 |
msgtyp | 结构体mtype值(必须大于0,随便写) |
msgflg | 一般为0(以默认的方式读取消息,读不到就阻塞) |
(5)msgctl—从内核中移除消息队列
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
成功返回0,失败返回-1;
一般写法: msgctl(msqid, IPC_RMID,NULL);