Bush
Bush

Reputation: 2533

Send signal with a delay to my own process in C on linux (ubuntu)

My program get lots of signals in a second. Yet, I want to be able to perform some code every second. If I just do:

toSleep = ONESEC;
while (toSleep > 0)
    toSleep = sleep(toSleep);

The signals that the program gets cause this while loop to starve.

If there could be some way to send my own process a signal every second that would be perfect because that signal will wait in the signal queue to take place in it's turn.

How can I do that?

Upvotes: 0

Views: 2102

Answers (1)

William Pursell
William Pursell

Reputation: 212198

Have a child send the signal. A trivial example with no error checking (also, you should use sigaction instead of signal):

#include <stdio.h>
#include <signal.h>

void handle( int s ) { return; }
int main( void ) {
    if( fork()) {
        while( 1 ) {
            signal( SIGUSR1, handle );
            pause();
            printf( "Signal received\n" );
        }
    } else {
        while( 1 ) {
            sleep( 1 );
            kill( getppid(), SIGUSR1 );
        }
    }
    return 0;
}

Also, rather than sending a signal, you might consider having the child write into a pipe (or use signalfd() if that is available) and then block on a read. It is sometimes significantly cleaner to avoid signals entirely.

Upvotes: 3

Related Questions