2011-05-04 99 views
0

我有兩個程序通過IPC隊列來回發送和接收消息。但是,有時msgrcv函數會收到一條空白消息,而不是接收實際通過隊列發送的內容。我已經註釋了一個我認爲應該可以工作的修復程序,但我想在此查看,看看這是否是使用msgrcv和msgsnd的正確方法。msgrcv獲取空白郵件

msgrcv:

int readqueue(int qid, long type, char *msg) 
{ 
    int retval; 

    // Current fix for blank messages 
    /* strcpy(MsgQueue.Message, ""); 

    while (strcmp(MsgQueue.Message, "") == 0) 
    { 
     retval = msgrcv(qid, &MsgQueue, MSGSIZE, (long)type, 0); 

     if (strcmp(MsgQueue.Message, "") == 0) 
      printf("msgrcv fail\n"); 
    }*/ 

    retval = msgrcv(qid, &MsgQueue, MSGSIZE, (long)type, 0); 
    strcpy(msg, MsgQueue.Message); 

    return retval; 
}



的msgsnd:

int sendqueue(int qid, long type, char *msg) 
{ 
    struct msqid_ds stat_buf, *pstat_buf; 
    int av, retval; 

    pstat_buf = &stat_buf; 
    av = 0; 

    /* Make sure there's space in the queue */ 
    do 
    {     
     retval = msgctl(qid, IPC_STAT, pstat_buf); 
     if (retval == -1) 
     { 
      fprintf(stderr, "msgctl in sendqueue failed! Error = %d\n", errno); 
      return retval; 
     } 
    } while (pstat_buf->msg_qbytes - pstat_buf->msg_cbytes == 0); 

    strcpy(MsgQueue.Message, msg); 
    MsgQueue.MsgType = (long)type; 

    retval = msgsnd(qid, &MsgQueue, MSGSIZE, 0); 

    memset(MsgQueue.Message, '\0', MSGSIZE-1); 
    return retval; 
}

回答

1

你說:「不過,有時msgrcv函數會得到一個空白的消息,而不是接收什麼實際上是通過發送隊列「

我會建議找出ou t實際發生的情況是調試問題的方式。

msgrcv將返回讀取的字節數或-1錯誤...您應該檢查並查看實際發生了什麼。

如果它是-1,errno被設置,並且有很多事情可以告訴你。手冊頁列出了它們全部。

+0

msgrcv接收128字節,這是爲隊列消息設置的最大字節大小。然而,字符串似乎仍然不時出現空白。 – Zac 2011-05-04 21:48:14