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
  • 相关阅读:
    leetcode-Binary Tree Inorder Traversal
    leetcode- Isomorphic Strings
    Ascii码表对应(摘至百度)
    leetcode-Happy Number
    leetcode-Bulls and Cows
    leetcode-Group Anagrams
    14、排序:插入类排序和交换类排序
    13、自平衡二叉查找树AVL
    11、创建Huffman树,生成Huffman编码
    10、二叉树的遍历+查找
  • 原文地址:https://www.cnblogs.com/scue/p/3055751.html
Copyright © 2011-2022 走看看