Domanda

Ho due programmi che inviano e ricevono messaggi avanti e indietro l'uno dall'altro tramite code IPC. Tuttavia, a volte la funzione MSGRCV riceverà un messaggio vuoto invece di ricevere ciò che è stato effettivamente inviato attraverso la coda. Ho commentato una soluzione che penso dovrebbe funzionare, ma volevo controllare qui e vedere se questo è il modo corretto di utilizzare MSGRCV e MSGSND.

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;
}
È stato utile?

Soluzione

Tu dici: "Tuttavia, a volte la funzione MSGRCV riceverà un messaggio vuoto invece di ricevere ciò che è stato effettivamente inviato attraverso la coda"

Suggerirei di capire cosa sta realmente accadendo come il modo di eseguire il debug del tuo problema.

msgrcv restituirà il numero di byte letti o -1 In errore ... dovresti verificarlo e vedere cosa sta realmente succedendo.

Se è -1, errno Viene impostato e ci sono diverse cose che può dirti. La pagina Man li elenca tutti.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top