#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <signal.h> void message( void *ptr ); void sig_handler(int signum); char *message1 = "thread1"; int main() { pthread_t thread1; int ret_thrd1; void *retval; ret_thrd1 = pthread_create(&thread1, NULL, (void *)&message, (void *) message1); int tmp1 = pthread_join(thread1, &retval); printf("thread start"); signal(SIGINT,sig_handler); pause(); } void message( void *ptr ) { int i = 0; for(i=0;i<5;i++) { printf("%d,%s\n",i,(char*)ptr); } } void sig_handler(int signum) { if(0 > signum) { fprintf(stderr,"sig_handler param err. [%d]\n",signum); return; } if(SIGINT == signum) { printf("Received signal [%s]\n",SIGINT==signum?"SIGINT":"Other"); } if(SIGQUIT == signum) { printf("Received signal [%s]\n",SIGQUIT==signum?"SIGQUIT":"Other"); } return; }
相比上一节代码,增加绿色部分,当按Ctrl+C 时,就会输出信息