文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>进程通信----消息队列

进程通信----消息队列

时间:2010-08-26  来源:huazaicola

进程通信----消息队列 流程:   创建写消息进程 1.ftok获取消息队列键值key 2.创建队列 3.创建消息结构,将要发送的数据赋值 3.发送消息     创建读消息进程 1.ftok获取同上相同消息队列的key 2.创建相同消息队列 3.接受消息 4.从内核中移除消息队列   发送进程代码:  

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

struct msg_buf
{
    long mtype;
    char mtext[255];
};
/*
 * signal handle funciton
*/
void func(int sign_no)
{
    if(sign_no == SIGBUS)
    {
        printf("get the signal!\n");
    }
}

main(void)
{
    key_t key;
    int msgid;
    struct msg_buf msgbuf;    

    key = ftok("./msg", 'a');
    if((msgid = msgget(key, IPC_CREAT | 0666)) < 0) //create the same queue with reading process

    {
        printf("msgget error");
        exit(1);
    }
    msgbuf.mtype = getpid(); //getpid for sending to reading process

    strcpy(msgbuf.mtext, "hello hua zai");
    if(msgsnd(msgid, &msgbuf, sizeof(msgbuf), IPC_NOWAIT) < 0)
    {
        printf("msgsnd error:%s\n", strerror(errno));
        exit(1);
    }
    printf("send %s to queue\n", msgbuf.mtext);
    
    signal(SIGBUS, func); //register the signal

    pause(); //waiting for signal

//    printf("process waked up!\n");

}


接受进程代码:

#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/ipc.h>
#include<signal.h>
struct msg_buf
{
        long mtype;
        char mtext[255];
};

main(void)
{
        key_t key;
        int msgid;
        struct msg_buf msgbuf;
        key = ftok("./msg", 'a');    //use ftok to get the key

        if((msgid = msgget(key, IPC_CREAT | 0666)) < 0)
        {
                printf("msgget error\n");
                exit(1);
        }
        if(msgrcv(msgid, &msgbuf, sizeof(msgbuf), 0, IPC_NOWAIT) < 0) //get address of struct, &msgbuf

        {
                printf("msgrcv error:%s\n", strerror(errno));
                exit(1);
        }
        printf("reveive %s from queue\n", msgbuf.mtext);
    kill(msgbuf.mtype, SIGBUS); //seng message to another process

    sleep(5);

        if(msgctl(msgid, IPC_RMID, 0) < 0)
        {
                printf("msgctl error\n");
                exit(1);
        }
        printf("queue is cancle!\n");
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载