Skip to content
Advertisement

Signal and output in c

Some time ago I found this exercise in C: without changing the main function, so that receiving a SIGUSR1 signal output is directed and added to a file in append mode as the first parameter. At the reception of another SIGUSR1 the output is directed to the console, and so on. How do such an exercise?

#include <stdio.h>
#include <time.h>
void redirectsetup (char *s){
}
int main (int argc, char *argv[]){
    redirect setup(argv[1]);
    while(1){
       time_t now = time(NULL);
       printf("%s",ctime(&now));
       sleep(1);
    }
}

Advertisement

Answer

I’ll give you some general pointers.

You need to install a signal handler. Try typing man signal or googling “signal handler linux”. As a rule your signal handler should do the minimum possible, many things are illegal in signal handlers including much of the C library. In this case, you could have it set a variable which tells you where to direct output and leave it at that.

Your main program needs to loop, sending characters to wherever the variable tells it.

One thing you might need to be careful of is a signal interrupting a system call, requiring it to be retried.

Have a go and see if you can make it work.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement