File: pth_cancel2.c

package info (click to toggle)
valgrind 1:3.12.0~svn20160714-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 120,428 kB
  • ctags: 70,855
  • sloc: ansic: 674,645; exp: 26,134; xml: 21,574; asm: 7,570; cpp: 7,567; makefile: 7,380; sh: 6,188; perl: 5,855; haskell: 195
file content (101 lines) | stat: -rw-r--r-- 2,145 bytes parent folder | download | duplicates (10)
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/********************************************************
 * An example source module to accompany...
 *
 * "Using POSIX Threads: Programming with Pthreads"
 *     by Brad nichols, Dick Buttlar, Jackie Farrell
 *     O'Reilly & Associates, Inc.
 *
 ********************************************************
 * async_safe --
 *
 * Example showing macro wrappers for calling non-async
 * safe routines when the caller has asynchronous 
 * cancellation turned on
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include <pthread.h>


#define async_cancel_safe_read(fd,buf,amt) \
   { \
      int oldtype; \
      pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype); \
      if (read(fd,buf,amt) < 0) \
         perror("read"),exit(1); \
      pthread_setcanceltype(oldtype,NULL); \
      pthread_testcancel(); \
   } 
   

#define async_cancel_safe_write(fd,buf,amt) \
   { \
      int oldtype; \
      pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype); \
      if (write(fd,buf,amt) < 0) \
         perror("write"), exit(1); \
      pthread_setcanceltype(oldtype,NULL); \
      pthread_testcancel(); \
   }


static int fd;
   
void *io(void *arg)
{
   int *fd2=(int *)arg; 
   char buf[20]="String";
   int amt=20;

   for (;;) {
      async_cancel_safe_write(*fd2,buf,amt);
      async_cancel_safe_read(*fd2,buf,amt);
   }
   return(NULL);
}

void *killer(void *arg)
{ 
   pthread_t * target = (pthread_t *)arg;
   sleep(1);
   pthread_cancel(*target);
   return(NULL);
}

extern int
main(void)
{
   pthread_t io_thread, killer_thread;   

   //   extern void *io(void *);
   // extern void *killer(void  *);

   if ((fd = open(".ktemp",O_CREAT | O_RDWR, 0666)) < 0)
      perror("open"), exit(1);

   pthread_create(&io_thread, 
		  NULL,
		  io,
		  (void *)&fd);
   pthread_create(&killer_thread,
		  NULL,
		  killer,
		  (void *)&io_thread);

   pthread_join(io_thread, NULL);

   pthread_join(killer_thread,NULL);

   if ((close(fd)) < 0)
     perror("close"),exit(1);
   if ((unlink(".ktemp")) < 0)
     perror("unlink"),exit(1);

   return 0;
}