Signal handlers in C: function passing argument gets error “invalid use of expression” ?

Signal handlers:http://www.elook.org/programming/c/signal.html

One point to remember when using Signal handles: it is not possible to pass arguments to the signal handler function (call).

E.g, this “signal(SIGALRM, myfunction(argument));” will not work and may output “invalid use of expression”. So we can only use “signal(SIGALRM, myfunction);”

Now what if you want to pass variable value to the function call? One way I would recommend (easy way) is to store values in a global variable then use it in the function. Below is an example used to obtain time elapsed after several alarm signal calls with global variable “sec” being used in the function:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
int sec=0;
struct timeval t1, t2;
void numsec(){
gettimeofday(&t2,NULL);
sec= t2.tv_sec – t1.tv_sec;
printf(“num seconds elapsed:%d \n”, sec);
}
void main(){
long usec=0;
gettimeofday(&t1,NULL);

while (sec<6){
gettimeofday(&t2,NULL);
sec= t2.tv_sec – t1.tv_sec;
usec= t2.tv_usec – t1.tv_usec;
signal(SIGALRM, numsec);
alarm(2);
pause();
}
}

Please Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s