以一个聊天程序为例:
聊天的两端分别为进程server和进程client
server:
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define PROJ_ID 11
#define BUF_SIZE 256
#define EXIT_CODE 1
#define MSND_TYPE 1
#define RCV_TYPE 2
struct mymsgbuf{
long msgtype;
char buf[BUF_SIZE];
};
int main()
{
struct mymsgbuf msgbuf;
key_t key;
int pid;
int len;
bzero(&msgbuf, sizeof(msgbuf));
len = sizeof(msgbuf) - 4;
key = ftok(".", PROJ_ID);
if (-1 == key)
{
perror("ftok error:");
exit(EXIT_CODE);
}
pid = msgget(key, IPC_CREAT|0660);
if (-1 == pid)
{
perror("msgget error:");
exit(EXIT_CODE);
}
while(1)
{
bzero(&msgbuf, sizeof(msgbuf));
printf("server: ");
fgets(msgbuf.buf, BUF_SIZE, stdin);
msgbuf.buf[strlen(msgbuf.buf)-1] = '\0';
msgbuf.msgtype = MSND_TYPE;
len = sizeof(msgbuf) - 4;
if (-1 == msgsnd(pid, &msgbuf, len, 0))
{
perror("msgsnd error:");
break;
}
if ( strncmp("exit", msgbuf.buf, strlen("exit")) == 0)
{
sleep(1);
break;
}
bzero(&msgbuf, sizeof(msgbuf));
if (-1 == msgrcv(pid, &msgbuf, BUF_SIZE, RCV_TYPE, 0))
{
perror("msgrcv error:");
break;
}
printf("recv from client message:%s\n", msgbuf.buf);
}
msgctl(pid, IPC_RMID, NULL);
return 0;
}
client:
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define PROJ_ID 11
#define BUF_SIZE 256
#define EXIT_CODE 1
#define MSND_TYPE 2
#define RCV_TYPE 1
struct mymsgbuf{
long msgtype;
char buf[BUF_SIZE];
};
int main()
{
struct mymsgbuf msgbuf;
key_t key;
int pid;
int len;
bzero(&msgbuf, sizeof(msgbuf));
len = sizeof(msgbuf) - 4;
key = ftok(".", PROJ_ID);
if (-1 == key)
{
perror("ftok error:");
exit(EXIT_CODE);
}
pid = msgget(key, IPC_CREAT|0660);
if (-1 == pid)
{
perror("msgget error:");
exit(EXIT_CODE);
}
while(1)
{
bzero(&msgbuf, sizeof(msgbuf));
if (-1 == msgrcv(pid, &msgbuf, BUF_SIZE, RCV_TYPE, 0))
{
perror("msgrcv error:");
break;
}
printf("recv from server message:%s\n", msgbuf.buf);
if ( strncmp("exit", msgbuf.buf, strlen("exit")) == 0)
{
break;
}
bzero(&msgbuf, sizeof(msgbuf));
printf("client: ");
fgets(msgbuf.buf, BUF_SIZE, stdin);
if ( strncmp("exit", msgbuf.buf, strlen("exit")) == 0)
{
break;
}
msgbuf.buf[strlen(msgbuf.buf)-1] = '\0';
msgbuf.msgtype = MSND_TYPE;
if (-1 == msgsnd(pid, &msgbuf, strlen(msgbuf.buf)+1, 0))
{
perror("msgsnd error:");
break;
}
}
return 0;
}