进程间通讯的方式主要包括共享内存、消息队列、管道等,笔者具体实现了提到的三种。
下面是消息队列的具体应用:
//send1.c send2、send3只是更改了信息内容(即data.mtext)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/msg.h>
typedef struct msgdata{
long mtype;
char mtext[128];
}MsgData;
int main(){
int msgid=msgget((key_t)666,0664|IPC_CREAT);
assert(msgid!=-1);
MsgData data;
memset(&data,0,sizeof(MsgData));
data.mtype=1;
strcpy(data.mtext,"1111");
msgsnd(msgid,&data,sizeof(MsgData),0);
exit(0);
}
//recv.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/msg.h>
typedef struct msgdata{
long mtype;
char mtext[128];
}MsgData;
int main(){
int msgid=msgget((key_t)666,0664|IPC_CREAT);
assert(msgid!=-1);
MsgData data;
memset(&data,0,sizeof(MsgData));
msgrcv(msgid,&data,sizeof(MsgData)*2,1,0);
printf("data.type:%ld\n",data.mtype);
printf("data.text:%s\n",data.mtext);
//msgctl(msgid,IPC_RMID,NULL); 笔者选择在bash用命令手动关闭(ipcrm)
exit(0);
}