我为学校作业编写了以下代码 - 它编译并打印所有正确的消息。但只是出于我自己的好奇心,我想知道我的代码是否可以缩短并且仍然有效。我尝试使用“signal”而不是“sigaction”,但我听说“sigaction”比“signal”更受欢迎。此外,此分配需要 3 个处理程序。有人可以看看并给我一些提示吗?谢谢!
#define _POSIX_SOURCE
#define _BSD_SOURCE
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
static void sigHandler_sigusr1(int sig)
{
printf("Caught SIGUSR1\n"); //sig contains the signal number that was received
}
static void sigHandler_sigusr2(int sig)
{
printf("Caught SIGUSR2\n");
}
static void sigHandler_sigint(int sig)
{
printf("Caught SIGINT, Existing\n");
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
struct sigaction s1;
struct sigaction s2;
struct sigaction s3;
struct sigaction t;
s1.sa_handler = sigHandler_sigusr1;
sigemptyset(&s1.sa_mask);
s1.sa_flags = 0;
s2.sa_handler = sigHandler_sigusr2;
sigemptyset(&s2.sa_mask);
s2.sa_flags = 0;
s3.sa_handler = sigHandler_sigint;
sigemptyset(&s3.sa_mask);
s3.sa_flags = 0;
sigaction(SIGUSR1, &s1, &t);
sigaction(SIGUSR2, &s2, &t);
sigaction(SIGINT, &s3, &t);
kill(getpid(), SIGUSR1);
kill(getpid(), SIGUSR2);
kill(getpid(), SIGINT);
return 0;
}