首页 > 解决方案 > LINUX msgget 和 ftok

问题描述

您好,我正在尝试 IPC 练习。但我有问题......这是代码

Send_process.c(路径:/home/John/h1/send_process.c)

struct mymsgbuf {
    long mtype;
    char mtext[80];
};

int main(void) {
    key_t key;
    int msgid;
    struct mymsgbuf mesg;
    char inputmsg[80];

    if(msgid = msgget((key_t)123, IPC_CREAT | 0666) == -1) {
        perror("Failed to create new MessageQueue");
        exit(1);
    }
    printf("%d\n", msgid);

    mesg.mtype = 1;
    while(1) {
        printf("Enter Sending Message. (Input exit, programm terminate) : ");
        scanf("%s", inputmsg);
        strcpy(mesg.mtext, inputmsg);

        if(msgsnd(msgid, (void *)&mesg, sizeof(mesg.mtext), IPC_NOWAIT) == -1) {
            perror("msgsnd");
            exit(1);
        }

        if(strcmp(inputmsg, "exit") == 0) {
            printf("Sending Process Terminated\n");
            break;
        }
    }
    return 0;
}

Receive_process.c(路径:/home/John/h1/send_process.c)

struct mymsgbuf {
    long mtype;
    char mtext[80];
};

int main(void) {
    struct mymsgbuf inmsg;
    key_t key;
    int msgid;
    key = ftok("/home/John/h1/receive_process.c", 123);

    if((msgid = msgget(key,0666)) < 0 ) {   //here is error
        perror("msgget");
        exit(1);
    }
    printf("%d\n", msgid);
    while(1) {
        if(msgrcv(msgid, &inmsg, sizeof(inmsg.mtext), 0,0) == -1) {
            perror("Message Receive");
            exit(1);
        }
        printf("Received Message. Message is [%s]\n", inmsg.mtext);
        if(strcmp(inmsg.mtext, "exit") == 0 ) {
            printf("Receive_process end\n");
            exit(0);
        }
    }
    return 0;
}

Send_process 效果很好,但 Receive_process 效果不佳。问题是什么?

标签: linuxipc

解决方案


推荐阅读