日期:2014-05-16 浏览次数:20983 次
int pthread_kill(thread_t tid, int sig)
将信号sig发送到由tid指定的线程,tid所指定的线程必须与调用线程在同一个进程中。如果sig为零,将执行错误检查,但并不实际发送信号。此错误检查可用来检查tid的有效性。
返回值 成功之后返回0,否则返回非零。
1 #define _MULTI_THREADED
2 #include <pthread.h>
3 #include <stdio.h>
4 #include <signal.h>
5 #include <string.h>
6 #include "check.h"
7
8 #define NUMTHREADS 3
9 void sighand(int signo);
10
11 void *threadfunc(void *parm)
12 {
13 pthread_t self = pthread_self();
14 pthread_t tid;
15 int rc;
16
17 tid = self;
18 // pthread_getunique_np(&self, &tid);
19 printf("Thread 0x%.8x %.8x entered\n", tid);
20 errno = 0;
21 rc = sleep(30);
22 if (rc != 0 && errno == EINTR) {
23 printf("Thread 0x%.8x %.8x got a signal delivered to it\n",
24 tid);
25 return NULL;
26 }
27 printf("Thread 0x%.8x %.8x did not get expected results! rc=%d, errno=%d\n",
28 tid, rc, errno);
29 return NULL;
30 }
31
32 int main(int argc, char **argv)
33 {
34 int rc;
35 int i;
36 struct sigaction actions;
37 pthread_t threads[NUMTHREADS];
38
39 printf("Enter Testcase - %s\n", argv[0]);
40
41 printf("Set up the alarm handler for the process\n");
42 memset(&actions, 0, sizeof(actions));
43 sigemptyset(&actions.sa_mask);
44 actions.sa_flags = 0;
45 actions.sa_handler = sighand;
46
47 rc = sigaction(SIGALRM,&actions,NULL);
48 checkResults("sigaction\n", rc);
49
50 for(i=0; i<NUMTHREADS; ++i) {
51 rc = pthread_create(&threads[i], NULL, threadfunc, NULL);
52 checkResults("pthread_create()\n", rc);
53 }
54
55 sleep(3);
56 for(i=0; i<NUMTHREADS; ++i) {
57 rc = pthread_kill(threads[i], SIGALRM);
58 checkResults("pthread_kill()\n", rc);
59 }
60