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();
}
}

To print a particular row/line when using files C programming

This post is related to manipulation of files in C.
If for eg, you have a list of records where each record is stored on a single line, this part can be helpful for you.
I used ‘lseek’ function to go to the start position of the required record and ‘\n’ to detect a new line. The solution:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

void main(){

char buf[100];
int fd;
fd = open (“myfile.dat”,O_RDONLY);
ssize_t n1= read (fd, buf, 100);
printf(“%s\n”, buf);

int chosenrecord;
printf(“Enter record number: \n”);
scanf(“%d”, &chosenrecord);

int count=1;
int rowfound=0;
int endpos;
int startpos=0; //defaut value 0 is used only for 1st record as no ‘\n’ is found
int j=0;

for(int i=0; i<= strlen(buf); i++){

if (buf[i]==’\n’){
count++;
rowfound=0;
startpos= i;
}
if (count == chosenrecord && rowfound==0){
rowfound=1;

for (j=i+1; j<= strlen(buf); j++){
if (buf[j]==’\n’){ //
endpos=j;
break;
}
}

int lengthrecord= endpos-startpos;
printf(“Start position of the record: %d\n”, startpos);
printf(“End position of the record:%d\n\n\n”, endpos);
lseek(fd, startpos, SEEK_SET); //SEEK_SET from beginning of file, save all data after the start position of record

printf(“Details of chosen record: \n”);
char bufrecord[100];
read(fd, bufrecord, lengthrecord); //print till end of record using record length

printf(“%s\n”, bufrecord);

}

}
close (fd);
}