@lupnfer
2016-12-16T09:37:58.000000Z
字数 2339
阅读 845
Code
#include <signal.h>#include <errno.h>#include <pthread.h>#include <unistd.h>#include <sys/types.h>void sig_handler(int signum){static int j = 0;static int k = 0;static int m = 0;pthread_t sig_ppid = pthread_self();// used to show which thread the signal is handled in.if (signum == SIGUSR1) {printf("thread %ld, receive SIGUSR1 No. %d\n", sig_ppid, j);j++;//SIGRTMIN should not be considered constants from userland,//there is compile error when use switch case} else if (signum == SIGRTMIN) {printf("thread %ld, receive SIGRTMIN No. %d\n", sig_ppid, k);k++;} else if(signum == 60){//printf("thread %ld, receive SIG119 No. %d\n", sig_ppid, m);m++;}}/*void* worker_thread(){pthread_t ppid = pthread_self();pthread_detach(ppid);while (1) {printf("I'm thread %d, I'm alive\n", ppid);sleep(10);}}*/void* sigmgr_thread(void *pwaitset){sigset_t waitset, oset;sigset_t *pwaitsetEx = (sigset_t *)pwaitset;siginfo_t info;int rc, i;pthread_t ppid = pthread_self();pthread_detach(ppid);printf("I'm thread %d, I'm alive\n", ppid);sigemptyset(&waitset);sigaddset(&waitset, SIGRTMIN);sigaddset(&waitset, SIGUSR1);sigaddset(&waitset, 60);if (pthread_sigmask(SIG_BLOCK, &waitset, &oset) != 0) //信号屏蔽printf("!! Set pthread mask failed\n");while (1) {rc = sigwaitinfo(&waitset, &info);if (rc != -1) {printf("sigwaitinfo() fetch the signal - %d\n", rc);sig_handler(info.si_signo);} else {printf("sigwaitinfo() returned err: %d; %s\n", errno, strerror(errno));}}}int main(){sigset_t bset, oset;int i, rc;pid_t pid = getpid();pthread_t ppid;siginfo_t info;// Block SIGRTMIN and SIGUSR1 which will be handled in//dedicated thread sigmgr_thread()// Newly created threads will inherit the pthread mask from its creatorsigemptyset(&bset);sigaddset(&bset, SIGRTMIN);sigaddset(&bset, SIGUSR1);sigaddset(&bset, 60); //自定义信号量if (pthread_sigmask(SIG_BLOCK, &bset, &oset) != 0) //信号屏蔽printf("!! Set pthread mask failed\n");// Create the dedicated thread sigmgr_thread() which will handle// SIGUSR1 and SIGRTMIN synchronouslypthread_create(&ppid, NULL, sigmgr_thread, (void *)&bset);// Create 5 worker threads, which will inherit the thread mask of// the creator main thread/*for (i = 0; i < 5; i++) {pthread_create(&ppid, NULL, worker_thread, NULL);}*/while (1) {rc = sigwaitinfo(&bset, &info);if (rc != -1) {printf("sigwaitinfo() fetch the signal - %d\n", rc);sig_handler(info.si_signo);} else {printf("sigwaitinfo() returned err: %d; %s\n", errno, strerror(errno));}}// send out 50 SIGUSR1 and SIGRTMIN signalsfor (i = 0; i < 500; i++) {//kill(pid, SIGUSR1);sleep(10);}exit (0);}