2013-01-02 43 views
1

我正在學習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()函數的權限。但同樣的錯誤。提前致謝。 在此先感謝。

+0

'spock'與'kirk'有相同的工作目錄嗎? –

+0

這是我執行中的錯誤。他們工作得很好。謝謝Alex。 – raka

回答

4

ftok要求該文件存在,因爲它使用inode信息來構造密鑰。如果您將它們構建在不同的目錄中,則使用相對路徑指向kirk.c應正常工作,例如spock/spock.c包含斯波克代碼,kirk/kirk.c包含柯克代碼,在spock/spock.c你應該參考../kirk/kirk.c

+0

這是我的錯誤。不過謝謝。 – raka

0

也有同樣的問題。如果你想執行消息接收過程,你必須確保消息發送者也是在那時執行。否則,msgqueue(如果你曾經運行過message-sender)將被取消註冊並且id與它關聯將不再有效。因此,它有什麼神奇的。 Pozdr。