summaryrefslogtreecommitdiff
path: root/source/tests/test_interprocess.c
blob: 58044bf20187e26595f00e07a2d70d52d92c6bca (plain)
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
#include "../kit/shared_memory.h"
#include "../kit/threads.h"

#include <stdio.h>

#define NAME "kit_test_interprocess"

enum { DATA_SIZE = 64 };

enum { STATE_INIT, STATE_READY, STATE_DONE };

int run_writer() {
  kit_shared_memory_t mem = kit_shared_memory_open(
      SZ(NAME), DATA_SIZE, KIT_SHARED_MEMORY_CREATE);

  if (mem.status != KIT_OK) {
    printf("%s: kit_shared_memory_open failed.\n", __FUNCTION__);
    fflush(stdout);
    return 1;
  }

  mem.bytes[0] = STATE_INIT;
  for (int i = 1; i < DATA_SIZE; i++) mem.bytes[i] = i;
  mem.bytes[0] = STATE_READY;

  while (mem.bytes[0] != STATE_DONE) thrd_yield();

  return kit_shared_memory_close(&mem);
}

int run_reader() {
  kit_shared_memory_t mem;
  for (;;) {
    mem = kit_shared_memory_open(SZ(NAME), DATA_SIZE,
                                 KIT_SHARED_MEMORY_OPEN);
    if (mem.status == KIT_OK)
      break;
    thrd_yield();
  }

  if (mem.status != KIT_OK) {
    printf("%s: kit_shared_memory_open failed.\n", __FUNCTION__);
    fflush(stdout);
    return 1;
  }

  while (mem.bytes[0] != STATE_READY) thrd_yield();

  i32 status = 0;

  for (i32 i = 1; i < DATA_SIZE; i++)
    if (mem.bytes[i] != i) {
      printf("%s: wrong byte %d\n", __FUNCTION__, i);
      fflush(stdout);
      status = 1;
    }

  mem.bytes[0] = STATE_DONE;

  if (kit_shared_memory_close(&mem) != KIT_OK)
    status = 1;

  return status;
}

int main(int argc, char **argv) {
  if (argc != 2) {
    printf("Wrong number of command line arguments %d\n", argc);
    return 1;
  }

  if (strcmp(argv[1], "writer") == 0) {
    struct timespec t0;
    timespec_get(&t0, TIME_UTC);

    i32 status = run_writer();

    struct timespec t1;
    timespec_get(&t1, TIME_UTC);

    i64 sec  = t1.tv_sec - t0.tv_sec;
    i64 nsec = t1.tv_nsec - t0.tv_nsec;

    printf("Done in %.2lf msec\n",
           (sec * 1000000000 + nsec) * 0.000001);
    fflush(stdout);

    return status;
  }

  if (strcmp(argv[1], "reader") == 0)
    return run_reader();

  printf("Invalid command line argument \"%s\"\n", argv[1]);
  return 1;
}