//signaltest.c // 子线程阻塞,等待信号,然后输出字符串 // 主线程从键盘录入字符,给子线程发信号。 #include <stdio.h> #include <unistd.h> #include <signal.h> #include <pthread.h> #include <time.h> pthread_t tid; sigset_t set; void myfunc() { printf("hello\n"); } static void* mythread(void *p) { int signum; while(1){ sigwait(&set,&signum); if(SIGUSR1 == signum) myfunc(); if(SIGUSR2 == signum) { printf("I will sleep 2 second and exit\n"); sleep(2); break; } } } int main() { char tmp; void* status; sigemptyset(&set); sigaddset(&set,SIGUSR1); sigaddset(&set,SIGUSR2); sigprocmask(SIG_SETMASK,&set,NULL); pthread_create(&tid,NULL,mythread,NULL); while(1) { printf(":"); scanf("%c",&tmp); if('a' == tmp) { pthread_kill(tid,SIGUSR1); //发送SIGUSR1,打印字符串。 } else if('q'==tmp) { pthread_kill(tid,SIGUSR2); //发出SIGUSR2信号,让线程退出,如果发送SIGKILL,线程将直接退出。 pthread_join(tid,&status); //等待线程tid执行完毕,这里阻塞。 printf("finish\n"); break; } else continue; } return 0; } #include <signal.h> #include <unistd.h> #include <stdio.h> void sigroutine(int dunno) { /* 信号处理例程,其中dunno将会得到信号的值 */ switch (dunno) { case 1: printf("Get a signal -- SIGHUP "); break; case 2: printf("Get a signal -- SIGINT "); break; case 3: printf("Get a signal -- SIGQUIT "); break; } return; } int main() { printf("process id is %d ",getpid()); signal(SIGHUP, sigroutine); //* 下面设置三个信号的处理方法 signal(SIGINT, sigroutine); signal(SIGQUIT, sigroutine); for (;;) ; } #include <signal.h> #include <unistd.h> #include <stdio.h> #include <sys/time.h> int sec; void sigroutine(int signo) { switch (signo) { case SIGALRM: printf("Catch a signal -- SIGALRM "); break; case SIGVTALRM: printf("Catch a signal -- SIGVTALRM "); break; } return; } int main() { struct itimerval value,ovalue,value2; sec = 5; printf("process id is %d ",getpid()); signal(SIGALRM, sigroutine); signal(SIGVTALRM, sigroutine); value.it_value.tv_sec = 1; value.it_value.tv_usec = 0; value.it_interval.tv_sec = 1; value.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &value, &ovalue); value2.it_value.tv_sec = 0; value2.it_value.tv_usec = 500000; value2.it_interval.tv_sec = 0; value2.it_interval.tv_usec = 500000; setitimer(ITIMER_VIRTUAL, &value2, &ovalue); for (;;) ; } #include <stdio.h> #define SIG_DFL ((void(*)(int))0) #define SIG_IGN ((void(*)(int))1) int main() { int a = (int)SIG_DFL; int b = (int)SIG_IGN; printf("a = %d\n",a); //0 printf("b = %d\n",b); //1 return 0; }