0

We are using a System V message queue with the msgrcv function being called in blocking mode. We want to implement a timer on the blocking msgrcv function so that when the timer expires and we have not received a message, we can unblock msgrcv and continue execution.

Do you have any suggestions on how we can achive this by programming?

jschmier
  • 15,458
  • 6
  • 54
  • 72
rajesh
  • 21
  • 1
  • 4
  • possible duplicate of http://stackoverflow.com/questions/4110198/system-v-message-queue-timed-receive – jschmier Dec 30 '10 at 16:53

2 Answers2

2

I have solved this problem using alarm signal.

Please check the following program if it helps:

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;                               
}
rajesh
  • 21
  • 1
  • 4
  • Thanks, this may be the best solution to the problem. You may want to reset the alarm and the signal handler after your code, though, to not affect any code that runs afterwards. Also, it's important to note that a handler that does nothing (really) is necessary, otherwise the program will be terminated. – philipp2100 Aug 18 '22 at 15:22
  • For a multi-threaded program, there could also be threading issues. From `man signal`: "The effects of signal() in a multithreaded process are unspecified.". Using sigaction() instead may be a solution... – philipp2100 Aug 19 '22 at 07:48
0

signal handler has a int param:

void sigalrm_handler(int)
{
    printf("Alarm signal delivered !\n");
    return;
}
W.Perrin
  • 4,217
  • 32
  • 31