上一篇介绍了三种fd的概念,今天看一下signalfd的例子程序,直接上代码,稍后做一点说明。

#include <sys/signalfd.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#define handle_error(msg) \
   do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main(int argc, char *argv[])
{
   sigset_t mask;
   int sfd;
   struct signalfd_siginfo fdsi;
   ssize_t s;

   sigemptyset(&mask);
   sigaddset(&mask, SIGINT);
   sigaddset(&mask, SIGQUIT);

   if (sigprocmask(SIG_BLOCK, &mask, NULL) == -1)
       handle_error("sigprocmask");

   sfd = signalfd(-1, &mask, 0);
   if (sfd == -1)
       handle_error("signalfd");

   for (;;) {
       s = read(sfd, &fdsi, sizeof(struct signalfd_siginfo));
       if (s != sizeof(struct signalfd_siginfo))
           handle_error("read");

       if (fdsi.ssi_signo == SIGINT) {
           printf("Got SIGINT\n");
       } else if (fdsi.ssi_signo == SIGQUIT) {
           printf("Got SIGQUIT\n");
           exit(EXIT_SUCCESS);
       } else {
           printf("Read unexpected signal\n");
       }
   }
}
L17-L21:将感兴趣的信号加入到sigset_t中;

L24:调用signalfd,把信号集与fd关联起来,第一个参数为-1表示新建一个signalfd,不是-1并且是一个合法的signalfd表示向其添加新的信号。

L29:阻塞等待信号的发生并读取。根据读取的结果可以知道发生了什么信号。

struct signalfd_siginfo的结构
struct signalfd_siginfo {
	uint32_t ssi_signo;   /* Signal number */
	int32_t  ssi_errno;   /* Error number (unused) */
	int32_t  ssi_code;    /* Signal code */
	uint32_t ssi_pid;     /* PID of sender */
	uint32_t ssi_uid;     /* Real UID of sender */
	int32_t  ssi_fd;      /* File descriptor (SIGIO) */
	uint32_t ssi_tid;     /* Kernel timer ID (POSIX timers)
	uint32_t ssi_band;    /* Band event (SIGIO) */
	uint32_t ssi_overrun; /* POSIX timer overrun count */
	uint32_t ssi_trapno;  /* Trap number that caused signal */
	int32_t  ssi_status;  /* Exit status or signal (SIGCHLD) */
	int32_t  ssi_int;     /* Integer sent by sigqueue(3) */
	uint64_t ssi_ptr;     /* Pointer sent by sigqueue(3) */
	uint64_t ssi_utime;   /* User CPU time consumed (SIGCHLD) */
	uint64_t ssi_stime;   /* System CPU time consumed (SIGCHLD) */
	uint64_t ssi_addr;    /* Address that generated signal
							(for hardware-generated signals) */
	uint8_t  pad[X];      /* Pad size to 128 bytes (allow for
							 additional fields in the future) */
};
编译运行,可以看一下效果是不是很简单。

详细信息可以在linux下面:man signalfd,例子程序就是摘自man。

GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐