I want to know what happens to this program at POSITION A, POSITION B and POSITION C if one were to press CTRL-C at those positions. I know that you are supposed to implement a SIGINT, but I am not sure how exactly to implement it. Please help.
#include<stdio.h>
#include<signal.h>
#include<wait.h>
int x = 5;
void handler(int sig) {
x += 3;
fprintf(stderr, "inside %d ", x);
}
int main() {
fprintf(stderr, "start ");
// POSITION A
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGINT,&act,NULL);
// POSITION B
x += 2;
// POSITION C
fprintf(stderr, "outside %d", x);
return 0;
}
You can send yourself a signal with kill
and getpid
.
$ gcc -o t2 t.c && ./t2
signal 2
sent signal
#include<stdio.h>
#include<unistd.h>
#include<signal.h>
void handler(int sig) {
fprintf(stderr, "signal %d \n", sig);
}
int main() {
struct sigaction act;
act.sa_handler = handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGINT,&act,NULL);
kill(getpid(),SIGINT);
fprintf(stderr,"sent signal\n");
}
Use the kill
system call.
kill(getpid(), SIGINT);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.