0

我们正在使用 System V 消息队列,该msgrcv函数在阻塞模式下被调用。我们想在阻塞msgrcv函数上实现一个定时器,这样当定时器到期而我们还没有收到消息时,我们可以解除阻塞msgrcv并继续执行。

您对我们如何通过编程实现这一目标有什么建议吗?

4

2 回答 2

2

我已经使用警报信号解决了这个问题。

如果有帮助,请检查以下程序:

int msg_recv(int id, MSG_DATA *msgptr)
{

    int n;


    **alarm(2);**    //After 2 second msg_recv interrupt and return errno "Interrupted system call"

    n = msgrcv(id, (MSG_DATA *) msgptr, sizeof(MSG_DATA) , 0, 0);

    perror("Return from msgrcv");

    printf ("N = %d\n %d %s\n\n",n,errno,strerror(errno));

    if ( n < 0) //goto LOOP;  // This forces the interrupted msgrcv to repeat
    return(n);
}




void sigalrm_handler()
{
    printf("Alarm signal delivered !\n");

    return;
}




int  main();


int main()
{
   //signal (SIGALRM, times_up);         /* go to the times_up function  */
                                       /* when the alarm goes off.     */
   **signal(SIGALRM, sigalrm_handler);**     

   int msqid;                          /* return value from msgget() */   

   MSG_DATA msg_data;

   msqid = 0;



   printf("Ready to receive ... \n");

   **msg_recv(msqid, &msg_data);**

   printf("read message \n");


   return 0;                               
}
于 2011-01-21T07:09:56.210 回答
0

信号处理程序有一个 int 参数:

void sigalrm_handler(int)
{
    printf("Alarm signal delivered !\n");
    return;
}
于 2017-09-20T13:27:15.777 回答