pthread版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #define WhThreadHandle pthread_t #define WH_THREAD_DEF(_proc, _arg) void *_proc(void *_arg) #define whThreadCreate(_handle, _loop, _param) pthread_create(&_handle, NULL, _loop, _param) void cleanup(void *p) { printf("thread killed.\n"); } WH_THREAD_DEF(func1, arg) { int oldState; pthread_cleanup_push(cleanup, NULL); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldState); while (1) sleep(1); // here must call sleep, or else cleanup will not be called. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldState); pthread_cleanup_pop(0); // here if want cleanup called, set param to non-zero. return NULL; } WhThreadHandle threadHandle; void onSignal(int sign) { switch (sign) { case SIGINT: pthread_cancel(threadHandle); printf("process ctrl+c pressed.\n"); break; } } int main() { signal(SIGINT, onSignal); whThreadCreate(threadHandle, func1, 0); while (1) ; return 1; } |