以一个聊天程序为例:
聊天的两端分别为进程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] = '