#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handle(int signum, siginfo_t *info, void *p);
int main(void)
{
pid_t fpid;
union sigval value; // 待发送的附加信息
value.sival_int = 1942;
struct sigaction act; // 结构体中含接收到的信号和附加信息的处理函数(handle)
act.sa_sigaction = handle; // 处理函数(handle)
act.sa_flags = SA_SIGINFO; // 此成员为SA_SIGINFO时才会接受sigqueue发送的信号
fpid = fork();
if (fpid == -1) {
perror("MSG");
}
if (fpid == 0) {
sigqueue(getppid(), SIGINT, value); // 发送信号(SIGINT)和附加信息(value)给父进程
exit(0);
}
sigaction(SIGINT, &act, NULL);
for(;;) {
sleep(1);
}
return 0;
}
void handle(int signum, siginfo_t *info, void *p)
{
int num = 0;
num = info->si_value.sival_int;
printf("recv value %d\n", num);
printf("recv signal %d\n", signum);
}
/*
上面用到的系统调用如下:通过man手册都能查到
int sigqueue(pid_t pid, int sig, const union sigval value);
union sigval {
int sival_int;
void *sival_ptr;
};
int sigaction(int signum, const struct sigaction *act,
struct sigaction *oldact);
struct sigaction {
void (*sa_handler)(int);
void (*sa_sigaction)(int, siginfo_t *, void *);
sigset_t sa_mask;
int sa_flags;
void (*sa_restorer)(void);
};
siginfo_t {
int si_signo; /* Signal number *
int si_errno; /* An errno value *
int si_code; /* Signal code *
int si_trapno; /* Trap number that caused
hardware-generated signal
(unused on most architectures) *
pid_t si_pid; /* Sending process ID *
uid_t si_uid; /* Real user ID of sending process *
int si_status; /* Exit value or signal *
clock_t si_utime; /* User time consumed *
clock_t si_stime; /* System time consumed *
sigval_t si_value; /* Signal value *
int si_int; /* POSIX.1b signal *
void *si_ptr; /* POSIX.1b signal *
int si_overrun; /* Timer overrun count; POSIX.1b timers *
int si_timerid; /* Timer ID; POSIX.1b timers *
void *si_addr; /* Memory location which caused fault *
int si_band; /* Band event *
int si_fd; /* File descriptor *
}
*/
信号发送(sigqueue)和接收(sigaction)
最新推荐文章于 2023-07-11 15:13:32 发布