我正在學習IPC編程。作爲它的一部分我嘗試了以下兩個代碼去了解關於消息隊列....msgget()和ftok()的錯誤
消息隊列創建者或消息發送者
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("kirk.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */
while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
int len = strlen(buf.mtext);
/* ditch newline at end, if it exists */
if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
消息接收機
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main(void)
{
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("kirk.c", 'B')) == -1) { /* same key as kirk.c */
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0644)) == -1) { /* connect to the queue */
perror("msgget");
exit(1);
}
printf("spock: ready to receive messages, captain.\n");
for(;;) { /* Spock never quits! */
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("spock: \"%s\"\n", buf.mtext);
}
return 0;
}
上面的代碼可以在beej's guide for message queue找到。
當我嘗試執行「spock」msgget()時拋出一個錯誤:沒有這樣的文件或目錄。 ftok()有什麼問題嗎?我將文件的權限更改爲傳遞給msgget()函數的權限。但同樣的錯誤。提前致謝。 在此先感謝。
'spock'與'kirk'有相同的工作目錄嗎? –
這是我執行中的錯誤。他們工作得很好。謝謝Alex。 – raka