zoukankan      html  css  js  c++  java
  • [Linux] 进程通信消息队列

    /*
     * =====================================================================================
     *
     *       Filename:  msq.c
     *
     *    Description:  
     *
     *        Version:  1.0
     *        Created:  2013年05月03日 00时20分50秒
     *       Revision:  none
     *       Compiler:  gcc
     *
     *         Author:  linkscue (scue), 
     *   Organization:  
     *
     * =====================================================================================
     */
    
    
    #include    <stdio.h>
    #include    <stdlib.h>
    #include    <sys/types.h>
    #include    <sys/msg.h>
    #include    <sys/ipc.h>
    #include    <unistd.h>
    
    struct msg_buf {
        int mtype;
        char data[255];
    };
    
    /* 
     * ===  FUNCTION  ======================================================================
     *         Name:  main
     *  Description:  
     * =====================================================================================
     */
    int main ( int argc, char *argv[] )
    {
        key_t key;
        int msgid;
        int ret;
        
        struct msg_buf msgbuf;
    
        key=ftok("/tmp/msg", 'a');                  /* file to key */
        printf("key = [%x]\n",key);
    
        msgid=msgget(key,IPC_CREAT|0666);           /* get file key id */
        if (msgid == -1) {
            printf("create error\n");
            return -1;
        }
    
        msgbuf.mtype = getpid();                    /* use pid to type */
        strncpy(msgbuf.data, "test hehe", sizeof(msgbuf.data));
        printf("msgbuf.data is [%s]\n", msgbuf.data);
        ret=msgsnd(msgid, &msgbuf, sizeof(msgbuf.data), IPC_NOWAIT); /* send */
        if (ret == -1) {
            printf("send message error\n");
            return -1;
        }
    
        memset(&msgbuf, '\0', sizeof(msgbuf));
        ret=msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), msgbuf.mtype, IPC_NOWAIT ); /* receive */
        if (ret==-1) {
            printf("receive message error \n");
            return -1;
        }
    
        printf("receive message is %s\n", msgbuf.data);
        return EXIT_SUCCESS;
    }
    ------------
    微博:http://weibo.com/scue
    Github:http://github.com/scue
  • 相关阅读:
    js 跳转链接的几种方式
    js 指定分隔符连接数组元素join()
    Ajax async属性
    非负数正则表达式
    firefox因 HTTP 严格传输安全(HSTS)机制无法打开网页
    查看linux系统某宏的定义(另类)
    ctags高级用法
    ctags简明用法
    关于数组和指针的一道例题的解读
    让gcc和gdb支持intel格式的汇编
  • 原文地址:https://www.cnblogs.com/scue/p/3055751.html
Copyright © 2011-2022 走看看