#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGKEY 1234
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[64]; /* message data */
};
int main()
{
struct msgbuf mbuf;
int ret;
int msgid = msgget(MSGKEY, IPC_CREAT | IPC_EXCL);
if (-1 == msgid)
{
perror("msgget");
exit(1);
}
pid_t pid = fork();
if (-1 == pid)
{
perror("fork");
exit(1);
}
else if (0 == pid) //子进程发送
{
while (1)
{
memset(&mbuf, 0, sizeof(mbuf));
mbuf.mtype = 1; //消息类型
scanf("%s", mbuf.mtext);
ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
if (-1 == ret)
{
perror("msgsnd");
exit(1);
}
if (!strcmp(mbuf.mtext, "bye"))
{
mbuf.mtype = 2;
msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
break;
}
}
}
else //父进程接收
{
while (1)
{
memset(&mbuf, 0, sizeof(mbuf));
ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), 2, 0);
if (-1 == ret)
{
perror("msgrcv");
exit(1);
}
if (!strcmp(mbuf.mtext, "bye"))
{
kill(pid, 2);
break;
}
printf("\t\t\t%s\n", mbuf.mtext);
memset(&mbuf, 0, sizeof(mbuf));
}
}
sleep(1);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#define MSGKEY 1234
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[64]; /* message data */
};
int main()
{
struct msgbuf mbuf;
int ret;
int msgid = msgget(MSGKEY, 0);
if (-1 == msgid)
{
perror("msgget");
exit(1);
}
pid_t pid = fork();
if (-1 == pid)
{
perror("fork");
exit(1);
}
else if (0 == pid) //子进程发送
{
while (1)
{
memset(&mbuf, 0, sizeof(mbuf));
mbuf.mtype = 2; //消息类型
scanf("%s", mbuf.mtext);
ret = msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
if (-1 == ret)
{
perror("msgsnd");
exit(1);
}
if (!strcmp(mbuf.mtext, "bye"))
{
mbuf.mtype = 1;
msgsnd(msgid, &mbuf, sizeof(mbuf.mtext), 0);
break;
}
}
}
else //父进程接收
{
while (1)
{
memset(&mbuf, 0, sizeof(mbuf));
ret = msgrcv(msgid, &mbuf, sizeof(mbuf.mtext), 1, 0);
if (-1 == ret)
{
perror("msgrcv");
exit(1);
}
if (!strcmp(mbuf.mtext, "bye"))
{
kill(pid, 2);
break;
}
printf("\t\t\t%s\n", mbuf.mtext);
memset(&mbuf, 0, sizeof(mbuf));
}
}
return 0;
}