Chinaunix首页 | 论坛 | 博客
  • 博客访问: 651434
  • 博文数量: 128
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 1546
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-22 14:05
文章分类

全部博文(128)

文章存档

2012年(2)

2011年(51)

2010年(75)

分类: LINUX

2010-08-26 10:32:58

进程通信----消息队列
流程:
  创建写消息进程
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");
}


阅读(1626) | 评论(1) | 转发(0) |
0

上一篇:指向指针的指针 **p

下一篇:多线程

给主人留下些什么吧!~~

chinaunix网友2010-08-28 08:59:25

Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com