Skip to content

Instantly share code, notes, and snippets.

@bave
Last active February 15, 2019 20:40
Show Gist options
  • Save bave/b67d0b1f3574f5ae6f2bf1ad7dacdfdf to your computer and use it in GitHub Desktop.
Save bave/b67d0b1f3574f5ae6f2bf1ad7dacdfdf to your computer and use it in GitHub Desktop.
sigwaitとスレッドのサンプル
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/signalfd.h>
#define EV_MAX 16
bool _epoll_add(int ep, int fd, uintptr_t ptr)
{
int ret;
struct epoll_event ev;
memset(&ev, 0, sizeof(ev));
ev.events = EPOLLIN;
if (ptr == 0) {
ev.data.fd = fd;
} else {
ev.data.u64 = ptr;
}
ret = epoll_ctl(ep, EPOLL_CTL_ADD, fd, &ev);
if(ret == -1) {
return false;
}
return true;
}
bool _epoll_del(int ep, int fd)
{
int ret;
ret = epoll_ctl(ep, EPOLL_CTL_DEL, fd, NULL);
if(ret == -1) {
return false;
}
return true;
}
void* th_func(void* param)
{
int ret;
int ep_fd = epoll_create(EV_MAX);
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGUSR1);
int s_fd = signalfd(-1, &sigset, 0);
ret = _epoll_add(ep_fd, s_fd, 0);
if (ret == false) {
printf("failed _epoll_add()\n");
exit(EXIT_FAILURE);
}
struct epoll_event ev[EV_MAX];
for (;;) {
ret = epoll_wait(ep_fd, ev, EV_MAX, 1000);
if (ret == -1) {
// error
} else if (ret == 0) {
// timeout unit is [ms]
printf("thread_timeout: %lu\n", pthread_self());
} else {
// ev check
for (int i=0; i<ret; i++) {
if (ev[i].data.fd == s_fd) {
struct signalfd_siginfo s_buf;
ret = read(s_fd, &s_buf, sizeof(s_buf));
printf("epoll signal\n");
} else {
;
}
}
}
}
return NULL;
}
static bool _set_signal(sigset_t *sigset)
{
int ret;
sigemptyset(sigset);
ret = sigaddset(sigset, SIGUSR1);
if(ret == -1) {
perror("sigaddset");
return false;
}
ret = sigaddset(sigset, SIGHUP);
if(ret == -1) {
perror("sigaddset");
return false;
}
ret = sigaddset(sigset, SIGINT);
if(ret == -1) {
perror("sigaddset");
return false;
}
ret = sigaddset(sigset, SIGTERM);
if(ret == -1) {
perror("sigaddset");
return false;
}
ret = pthread_sigmask(SIG_BLOCK, sigset, NULL);
if(ret == -1) {
perror("sigaddset");
return false;
}
return 0;
}
int main()
{
int ret;
int retsig;
sigset_t sigset;
pthread_t tid;
pthread_create(&tid, NULL, th_func, NULL);
ret = _set_signal(&sigset);
if (ret != 0) {
printf("failed _set_signal()\n");
exit(EXIT_FAILURE);
}
while (1) {
ret = sigwait(&sigset, &retsig);
if (ret == 0){
printf("retsig:%d\n", retsig);
break;
}
}
printf("hogehoge\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment