File: timer2.c

package info (click to toggle)
dmtcp 2.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,496 kB
  • sloc: cpp: 33,592; ansic: 28,099; sh: 6,735; makefile: 1,950; perl: 1,690; python: 1,241; asm: 138; java: 13
file content (64 lines) | stat: -rw-r--r-- 1,412 bytes parent folder | download
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
/* Inspired from:
 * http://ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/sigev_thread.c
 */

#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <errno.h>
#include <pthread.h>
#include <sys/signal.h>
#include <sys/time.h>

timer_t timer_id;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;

void timer_thread (union sigval arg)
{
  sleep(1);

  assert_perror(pthread_mutex_lock (&mutex));
  printf ("Timer %d\n", counter++);
  assert_perror(pthread_mutex_unlock (&mutex));
}

int main()
{
  int status;
  struct itimerspec ts;
  struct sigevent se;

  /* Set the sigevent structure to cause the signal to be
   * delivered by creating a new thread.
   */
  se.sigev_notify = SIGEV_THREAD;
  se.sigev_value.sival_ptr = &timer_id;
  se.sigev_notify_function = timer_thread;
  se.sigev_notify_attributes = NULL;

  /* Specify a repeating timer that fires every 1 seconds. */
  ts.it_value.tv_sec = 1;
  ts.it_value.tv_nsec = 0;
  ts.it_interval.tv_sec = 1;
  ts.it_interval.tv_nsec = 0;

  printf("Creating timer\n");
  status = timer_create(CLOCK_REALTIME, &se, &timer_id);
  if (status == -1) {
    assert_perror(errno);
  }

  printf("Setting timer %p for 1-second expiration...\n", (void *)timer_id);
  status = timer_settime(timer_id, 0, &ts, 0);
  if (status == -1) {
    assert_perror(errno);
  }

  while (1) {
    sleep(1);
  }

  return 0;
}