您的位置:首页 > 运维架构 > Linux

Linux多线程学习(九)pthread_kill

2012-09-11 12:52 393 查看
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

61 for(i=0; i<NUMTHREADS; ++i) {

62 rc = pthread_join(threads[i], NULL);

63 checkResults("pthread_join()\n", rc);

64 }

65 printf("Main completed\n");

66 return 0;

67 }

68

69 void sighand(int signo)

70 {

71 pthread_t self = pthread_self();

72 pthread_t tid;

73

74 //pthread_getunique_np(&self, &tid);

75 tid = self;

76 printf("Thread 0x%.8x %.8x in signal handler\n",

77 tid);

78 return;

79 }

编译 gcc -o pthread_kill -lpthread pthread_kill.c

运行结果

Enter Testcase - ./pthread_kill

Set up the alarm handler for the process

Thread 0xb7f0cba0 00000000 entered

Thread 0xb750bba0 00000000 entered

Thread 0xb6b0aba0 00000000 entered

Thread 0xb7f0cba0 00000000 in signal handler

Thread 0xb7f0cba0 00000000 got a signal delivered to it

Thread 0xb750bba0 00000000 in signal handler

Thread 0xb750bba0 00000000 got a signal delivered to it

Thread 0xb6b0aba0 00000000 in signal handler

Thread 0xb6b0aba0 00000000 got a signal delivered to it

Main completed
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: