【C语言】【unix c】两个进程通过消息队列实现进程间的通信

send.c:
    #include 
    #include 
    #include 
    #include 
    #include 
    typedef struct msgbuf{ //函数要求用户自定义一个结构体
        long mtype;
        char mtext[128];//默认128个空间
    }msg_t;

    int main(void) {
        key_t key; //为了接收键值以确定ID
        msg_t mbuf;
        key = ftok(".",21);  //获得一个键值
        if(key == -1) {
        perror("ftok");
        return -1;
        }
        printf("key=%x\n",key);
        //从内核获取消息队列
        int msqid = msgget(key, IPC_CREAT|0664);
        if(msqid == -1) {
        perror("MSGGET");
        return -1;
        }
        printf("msqid=0x%x\n",msqid);
       //初始化消息
        mbuf.mtype = 3;
        strcpy(mbuf.mtext,"this is a test\n");
        //向消息队列发送消息
        int s = msgsnd(msqid, &mbuf, strlen(mbuf.mtext)+1, 0);
        if(s == -1) {
        perror("msgsnd");
        return -1;
        }

        return 0;
        }
命令: tarena@ubuntu:~/day/day33$ a.out 
结果: key=15081b76
    msqid=0x0
命令: tarena@ubuntu:~/day$ ipcs  //察看当前列对中所占的大小和消息数

    ------ Shared Memory Segments --------
    key        shmid      owner      perms      bytes      nattch     status      
    0x00000000 0          tarena     600        393216     2          dest         
    0x00000000 32769      tarena     600        393216     2          dest         

    ------ Semaphore Arrays --------
    key        semid      owner      perms      nsems     

    ------ Message Queues --------
    key        msqid      owner      perms      used-bytes   messages    
    0x15081b76 0          tarena     664        15           1            //执行一次,写入一次消息,再执行一次会继续追加

recv.c:
    #include 
    #include 
    #include 
    #include 
    #include 
    typedef struct msgbuf{
        long mtype;
        char mtext[128];
    }msg_t;

    int main(void) {
        key_t key;
        msg_t mbuf;
        key = ftok(".",21);
        if(key == -1) {
        perror("ftok");
        return -1;
        }
        printf("key=%x\n",key);
        //从内核获取消息队列
        int msqid = msgget(key, IPC_CREAT|0664);
        if(msqid == -1) {
        perror("MSGGET");
        return -1;
        }
        printf("msqid=0x%x\n",msqid);
        //从消息队列获取消息
        int s = msgrcv(msqid, &mbuf, 128, 3, IPC_NOWAIT);//0是没有消息阻塞,IPC_NOWAIT是没有消息不阻塞
        if(s == -1) {
        perror("msgrcv");
        return -1;
        }
        printf("%s\n", mbuf.mtext);
        return 0;
    }

    tarena@ubuntu:~/day/day33$ rec
    key=15081b76
    msqid=0x0
    this is a test  //第一次消息列对里有消息

    tarena@ubuntu:~/day/day33$ rec
    key=15081b76
    msqid=0x0
    msgrcv: No message of desired type  //第二次消息列对里没有消息,提示没有消息。

你可能感兴趣的:(c语言,Linux)