Chinaunix首页 | 论坛 | 博客
  • 博客访问: 205352
  • 博文数量: 35
  • 博客积分: 2691
  • 博客等级: 少校
  • 技术积分: 527
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-11 09:42
文章分类

全部博文(35)

文章存档

2012年(5)

2010年(6)

2009年(2)

2008年(22)

我的朋友

分类: C/C++

2010-01-19 13:34:40

 

//2010-01-19 姚建明

//util.h

#define KEY 0x888

struct MsgBuf {
    int m_nType;
    int m_nCode;
    char m_szName[128];
};

//client.cpp

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "util.h"

int main()
{
    int nSndId = msgget(KEY, 0);
    int nRcvId = msgget(IPC_PRIVATE, IPC_CREAT);
    if (nSndId < 0 || nRcvId < 0) {
        perror("msgget");
        exit(1);
    }

    struct MsgBuf sndBuf;
    sndBuf.m_nType = nRcvId;
    sndBuf.m_nCode = 10;
    strcpy(sndBuf.m_szName, "hello world");
    msgsnd(nSndId, &sndBuf, sizeof(sndBuf), 0);

    struct MsgBuf rcvBuf;
    msgrcv(nRcvId, &rcvBuf, sizeof(rcvBuf), 0, MSG_NOERROR);
    printf("code: %d\n", rcvBuf.m_nCode);
    printf("name: %s\n", rcvBuf.m_szName);
    msgctl(nRcvId, IPC_RMID, NULL);

    return 0;
}

//server.cpp

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <signal.h>

#include <string>
using namespace std;

#include "util.h"

int g_nId;

static void interrupt_handler(int sig)
{
#ifdef SA_NOCLDSTOP
    struct sigaction sigact;

    sigact.sa_handler = SIG_DFL;
    sigemptyset(&sigact.sa_mask);
    sigact.sa_flags = 0;
    sigaction(sig, &sigact, NULL);
#else
    signal(sig, SIG_DFL);
#endif
    msgctl(g_nId, IPC_RMID, NULL);
    kill(getpid(), sig);
}

static void install_handler(int sig_num, void (*sig_handler) (int sig))
{
#ifdef SA_NOCLDSTOP
    struct sigaction sigact;
    sigaction(sig_num, NULL, &sigact);
    if (sigact.sa_handler != SIG_IGN) {
        sigact.sa_handler = sig_handler;
        sigemptyset(&sigact.sa_mask);
        sigact.sa_flags = 0;
        sigaction(sig_num, &sigact, NULL);
    }
#else
    if (signal(sig_num, SIG_IGN) != SIG_IGN)
        signal(sig_num, sig_handler);
#endif
}

int main()
{
    install_handler(SIGINT, interrupt_handler);

    if ((g_nId = msgget(KEY, IPC_CREAT)) < 0) {
        perror("msgget");
        exit(1);
    }

    while(1) {
        struct MsgBuf oBuf;
        int nRtn = msgrcv(g_nId, &oBuf, sizeof(oBuf), 0 ,MSG_NOERROR);
        if (nRtn < 0) {
            perror("msgrcv");
            exit(1);
        }

        pid_t pid = fork();
        if (pid == 0) {
            printf("code: %d\n", oBuf.m_nCode);
            printf("name: %s\n", oBuf.m_szName);

            int nId = oBuf.m_nType;
            msgsnd(nId, &oBuf, sizeof(oBuf), 0);
        }

        sleep(2);
    }
}


阅读(1225) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~