#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("../5_进程间通信/1/",2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n",key);
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n",msqid);
struct msgbuf snd;
struct msgbuf rcv;
ssize_t res = 0;
while(1)
{
printf("输入数据类型>>> ");
scanf("%ld",&snd.mtype);
getchar();
if(snd.mtype <= 0)
{
break;
}
printf("输入信息内容>>> ");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
if(msgsnd(msqid,(void*)&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("发送信息成功\n");
res = msgrcv(msqid,&rcv,sizeof(rcv.mtext),0,0);
if(res < 0)
{
perror("msgrcv");
break;
}
printf("%s\n",rcv.mtext);
}
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#define MSG_EXCEPT 020000
struct msgbuf
{
long mtype;
char mtext[128];
};
int main(int argc, const char *argv[])
{
key_t key = ftok("../5_进程间通信/1/",2);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key = %#X\n",key);
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid < 0)
{
perror("msgget");
return -1;
}
printf("msqid = %d\n",msqid);
struct msgbuf rcv;
struct msgbuf snd;
ssize_t res = 0;
while(1)
{
res = msgrcv(msqid,&rcv,sizeof(rcv.mtext),0,0);
if(res < 0)
{
perror("msgrcv");
break;
}
printf("%s\n",rcv.mtext);
printf("输入数据类型>>> ");
scanf("%ld",&snd.mtype);
getchar();
if(snd.mtype <= 0)
{
break;
}
printf("输入信息内容>>> ");
fgets(snd.mtext,sizeof(snd.mtext),stdin);
snd.mtext[strlen(snd.mtext)-1] = '\0';
if(msgsnd(msqid,(void*)&snd,sizeof(snd.mtext),0)<0)
{
perror("msgsnd");
return -1;
}
printf("发送信息成功\n");
}
system("ipcs -q");
return 0;
}