两无关系的进程运用消息队列进行通信
输入文件:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
struct msgbuf
{
long mtype; /* 放消息编号,必须 > 0 */
char mtext[1024]; /* 消息内容(消息正文) */
};
int main()
{
key_t key;
key = ftok(".", 'a');
printf("key = [%x]\n",key);
struct msgbuf msgbuf;
int msgid = msgget(key,IPC_CREAT | 0664);
char buffer[1024];
while(1)
{
printf("send to msg:\n");
memset(buffer, 0, sizeof(buffer));
gets(buffer);
msgbuf.mtype = 1;
strcpy(msgbuf.mtext,buffer);
//printf("%s\n",msgbuf.mtext);
//write(fd,mtext, strlen(mtext));
//int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
int ret = msgsnd(msgid,&msgbuf,sizeof(msgbuf.mtext),IPC_NOWAIT);
if(ret == -1)
{
perror("ret error\n");
exit(1);
}
}
pause();
return 0;
}
输出文件代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <fcntl.h>
struct msgbuf
{
long mtype; /* 放消息编号,必须 > 0 */
char mtext[1024]; /* 消息内容(消息正文) */
};
int main()
{
key_t key;
key = ftok(".", 'a');
int msgid = msgget(key,IPC_CREAT | 0664);
struct msgbuf msgbuf;
int i=1;
while(1)
{
memset(&msgbuf,0,sizeof(msgbuf));
int ret = msgrcv(msgid,&msgbuf,sizeof(msgbuf.mtext),i,0);
if(ret == -1)
{
perror("error\n");
return -1;
}
printf("recv from msg:[%s]\n",msgbuf.mtext);
}
pause();
return 0;
}
运行结果: