【问题标题】:Check a msqid to see if there is message without waiting or msgrcv检查一个 msqid 看是否有消息没有等待或 msgrcv
【发布时间】:2014-04-29 17:53:15
【问题描述】:

感谢大家的检查。

我想知道是否有任何方法可以检查消息队列 (msqid) 并查看队列中是否有任何消息。如果没有,我想继续。我能够在网上找到的唯一方法是使用带有 IPC_NOWAIT 的 msgrcv,但如果没有找到消息,则会抛出 ENOMSG。尽管没有消息,但我想继续。

我的代码太杂乱了,我无法发布并为此感到自豪,所以我将发布一些我想要发生的伪代码:

Main()
{
    Initialize queues;
    Initialize threads  //  4 clients and 1 server
    pthread_exit(NULL);
}
Server()
{
    while (1)
    {
        check release queue;  // Don't want to wait
        if ( release )
             increase available;
        else
             // Do nothing and continue

        Check backup queue;  // Don't want to wait
        if ( backup) 
            read backup; 
        else
            read from primary queue; // Will wait for message

        if ( readMessage.count > available )
            send message to backup queue;
        else
            send message to client with resources;
            decrease available;        
    } //Exit the loop
}

Client
{
    while(1)
    {
        Create a message;
        Send message to server, requesting an int;
        Wait for message;
        // Do some stuff
        Send message back to server, releasing int;
    } // Exit the loop
}

typedef struct {
    long to;
    long from;
    int count;
} request;

据我所知,您可以无限期地等待,也可以不等待就进行检查,如果没有任何内容则崩溃。我只想检查队列而不等待,然后继续。

您可以提供的任何和所有帮助将不胜感激!非常感谢!

【问题讨论】:

  • "... and crash ..." msgrcv() 不会使程序崩溃。它只会返回-1 并将errno 设置为ENOMSG

标签: c pthreads msg msgrcv


【解决方案1】:

你知道 C 不会“抛出”任何东西吗? ENOMSGerror 代码,而不是任何类型的异常或信号。如果msgrcv 返回-1,则使用errno 检查它。

你可以这样使用它:

if (msgrcv(..., IPC_NOWAIT) == -1)
{
    /* Possible error */
    if (errno == ENOMSG)
    {
        printf("No message in the queue\n");
    }
    else
    {
        printf("Error receiving message: %s\n", strerror(errno));
    }
}
else
{
    printf("Received a message\n");
}

【讨论】:

    猜你喜欢
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 2019-04-13
    • 2019-06-27
    • 1970-01-01
    • 2021-08-13
    相关资源
    最近更新 更多