how does the catchsignal know what signal it needs to ignore? thanks
catchsignal isn't part of POSIX UNIX, it sounds like a function inside a program - one somebody wrote.
Can you tell us what you are doing, and what you are trying to answer.
hey jim. my prof gave me this program...
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void catchsignal(int signo) {
char handmsg[] = "You cannot \"Ctrl-C\" me!\n";
int msglen = sizeof(handmsg);
write(STDERR_FILENO, handmsg, msglen);
}
int main() {
struct sigaction act;
act.sa_handler = catchsignal;
act.sa_flags = 0;
if ((sigemptyset(&act.sa_mask) == -1) ||
(sigaction(SIGINT, &act, NULL) == -1)) {
printf("Failed to set SIGINT to handle Ctrl-C");
}
while(1);
}
that program catches the signal Ctrl C which if I'm not mistaken is one of the kill commands in linux. i can't remember what specific kill command is that. my question is how does the catchsignal function learn which signal to ignore? thanks.
Only signal(s) you 'intercept' will be handled by catchsignal.
So you cant kill that program with ctrl-c but try delivering it signal like TERM
kill -TERM pid
and you'll see ...
yup, i know it wouldn't be able to ignore the sigterm...i just want to know how it intercept the ctrl-c...?
struct sigaction act;
act.sa_handler = catchsignal;
act.sa_flags = 0;
if ((sigemptyset(&act.sa_mask) == -1) ||
(sigaction(SIGINT, &act, NULL) == -1))
This bunch of statements is where the signal handler is being setup. The "act.sa_handler=catchsignal;" statement spells out the function that will be used (catchsignal). And the statement signaction(SIGINT,&act,NULL) specifies that values from the act structure are to be associated with the reception of SIGINT.
thank you very much.
one more question...how could i get out of the if loop in the statement above. say i want to have another catchsignal...?
Here's another way of writing the code:
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void catchsignal(int signo) {
fprintf(stdout,"Ha! Caught signal %d\n",signo);
}
int main() {
struct sigaction act;
act.sa_handler = catchsignal;
act.sa_flags = 0;
if(sigemptyset(&act.sa_mask)==-1) {
perror("error in sigemptyset!!\n");
}
if(sigaction(SIGINT,&act,NULL)==-1) {
perror("Failed to set SIGINT to handle Ctrl-C\n");
}
if(sigaction(SIGQUIT,&act,NULL)==-1) {
perror("Failed to set SIGQUIT to handle Ctrl-\\\n");
}
while(1);
}
You can just keep adding signals to that list.
As a side note - you might be better off with using write() in a signal handler.