进程间通信:消息队列

接收:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
struct msg_st{
    long int msg_type;
    char text[BUFSIZ];
};
int main(){
    int running = 1;
    int msgid = -1;
    struct msg_st data;
    long int msgtype = 4;
    
    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
    if(msgid == -1){
        fprintf(stderr, "msgget failed with error: %d\n", errno);
        exit(EXIT_FAILURE);
    }
    
    while(running){
        data.msg_type = 8;
        if(msgrcv(msgid, (void*)&data, BUFSIZ, msgtype, 0) == -1){
           fprintf(stderr, "msgrcv failed with errno: %d\n", errno);
            exit(EXIT_FAILURE);
        }
        printf("You wrote: %s\n",data.text);
      
        if(strncmp(data.text, "end", 3) == 0){
            running = 0;
        }
    }
    
    if(msgctl(msgid, IPC_RMID, 0) == -1){
        fprintf(stderr, "msgctl(IPC_RMID) failed\n");
        exit(EXIT_FAILURE);
    }
    exit(EXIT_SUCCESS);
}

发送:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <errno.h>
#define MAX_TEXT 512
struct msg_st{
    long int msg_type;
    char text[MAX_TEXT];
};
int main(){
    int running = 1;
    struct msg_st data;
    char buffer[BUFSIZ];
    int msgid = -1;

    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
    if(msgid == -1){
        fprintf(stderr, "msgget failed with error: %d\n", errno);
        exit(EXIT_FAILURE);
    }
    while(running){
        printf("Enter some text: ");
        fgets(buffer, BUFSIZ, stdin);
        data.msg_type = 4;
        strcpy(data.text, buffer);
 
        if(msgsnd(msgid, (void*)&data, MAX_TEXT, 0) == -1){
            fprintf(stderr, "msgsnd failed\n");
            exit(EXIT_FAILURE);
        }
        
        if(strncmp(buffer, "end", 3) == 0)
            running = 0;
        sleep(1);
    }
    exit(EXIT_SUCCESS);
}

posted on 2017-03-20 11:36  杜聪  阅读(166)  评论(0)    收藏  举报

导航