LINUX msgget和ftok

时间:2018-10-27 10:10:00

标签: linux ipc

您好,我正在尝试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效果不好。有什么问题吗?

0 个答案:

没有答案