#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
typedef struct msg_t
{
long type;//必须为整型(int或 long 或无符号),不能为chr
char name[20];
char mtext[50];
}MSG;
int main(void)
{
struct msqid_ds tmpbuf;//struct msqid_ds是系统定义的结构体可以 man msgctl 查看
key_t key;
int msgqid, ret;
MSG msg;
pid_t pid;
long chr;
char buf[100];
strcpy(msg.name,"Lucy");
//IPC_RMID();
key = ftok(".", 12);
if (key < 0)
{
perror("ftok");
}
msgqid = msgget(key, IPC_CREAT|0666);
if (msgqid < 0)
{
perror("msgget");
//exit(0);
}
printf("\rLucy:");
pid=fork();
if(pid==-1)
perror("fork");
if(pid==0)
{ sleep(1);
while(1)
{
//printf("test2\n");//!!!!
// sleep(1);
ret = msgrcv(msgqid, &msg, sizeof(msg.mtext)+sizeof(msg.name), (long int)('L'), 0);
//printf("%s\n",msg.name);
if (ret < 0)
perror("msgsnd");
if(ret>0)
{
printf("\r%s:%s\n",msg.name,msg.mtext);
printf("\rLucy:");
fflush(stdout);
}
}
}
while(1)
{
//printf("\rLucy:");
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%c %s",&chr,buf);
strcpy(msg.mtext, buf);
msg.type=chr;
printf("----------%s %c--------\n",msg.mtext,msg.type);
if((chr=='B')||(chr=='L')||(chr=='P'))
{
printf("test\n");
ret=msgsnd(msgqid,&msg,sizeof(msg.mtext)+sizeof(msg.name),IPC_NOWAIT);
if (ret < 0)
perror("msgsnd");
printf("test1\n");
//fflush(stdout);
}
if (ret < 0)
perror("msgsnd");
//printf("test2\n");
printf("\rLucy:");
fflush(stdout);
}
msgctl(msgqid,IPC_RMID,&tmpbuf);//!!!
return 0;
}