Firstly your way of setting a signal handler using sigaction()
is not correct as you didn't fill all the member of struct sigaction
. Fill all required member
struct sigaction info;
info.sa_handler = sigintHandler;
sigaction(SIGINT,&info,NULL);
Secondly, to read data from fifo
file while loop is not required as you are reading MAX_BUF
at a time. Loop is not required, read like this
int ret = read(fd, buf, MAX_BUF);
buf[ret-1] = '\0'; /*it should be null terminated */
Thirdly, sigintHandler()
excepts only one argument. From the manual page of sigaction()
struct sigaction {
void (*sa_handler)(int); /*handler expects only 1 argument */
/* other member */
}
Finally & most importantly it is not safe to call functions like printf()
& exit()
from within a signal handler.
your sigHandler()
looks like
static void sigintHandler(int sig_num) {
write(1,"in isr\n",strlen("in isr\n"));
/* set some flag variable here & use that
flag variable in main() function to remove the fifo */
}
see this How to avoid using printf in a signal handler?
Here is the example code
static int fifo_flag = 0;
static void sigintHandler(int sig_num) {
write(1,"in isr\n",strlen("in isr\n"));
fifo_flag = 1;
}
int main(void){
printf("Access-Control-Allow-Origin: *\n");
printf("Content-Type: text/event-stream\n\n");
int fd = 0, index = 0;
char buf[MAX_BUF];
#if 0
char *myfifo = "data";
#endif
//char * myfifo = "/tmp/omcipipe";
struct stat st;
struct sigaction info;
info.sa_handler = sigintHandler;
//info.sa_flags = /* set to defaulgs a/c to your requirement*/
if (stat(myfifo, &st) != 0) {
mkfifo(myfifo, 0666);
perror("mkfifo");
}
fd = open(myfifo, O_RDONLY | 0666);
if(fd == -1){
perror("open");
return 0;
}
char ch = 0;
while(read(fd, &ch, 1) > 0) {
sigaction(SIGINT,&info,NULL);/* if ctrl+c is called */
buf[index] = ch;
//sleep(1);/* just to observe ctrl+c behaviour, not advised to use */
printf("%c\n",buf[index]);
index++;
}
buf[index] = '\0';
printf("data: %s", buf);
printf("\n");
puts( "----closing----");
close(fd);
if(fifo_flag == 1) { /*if flag is set, unlink fifo */
unlink(myfifo); /* you can unlink fifo file here */
}
return 0;
}