File: shared-memory1.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 (76 lines) | stat: -rw-r--r-- 1,609 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
65
66
67
68
69
70
71
72
73
74
75
76
// _DEFAULT_SOURCE for mkstemp  (WHY?)
#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

// For open()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


void reader(int fd);
void writer(int fd);

int main() {
  char filename[] = "dmtcp-shared-memory.XXXXXX";
  int fd;

  fd = mkstemp(filename);
  printf("creating temporary file in local directory: %s\n", filename);
  //printf("creating file: %s\n", "/tmp/dmtcp-shared-memory.dat");
  unlink(filename);
  //if (-1 == unlink(filename)) {
  //  perror("unlink");
  //  exit(1);
  //}
  //fd = open("/tmp/dmtcp-shared-memory.dat", O_RDWR | O_CREAT, S_IREAD|S_IWRITE);
  // if (fd == -1) perror("open");
  /* Extend file to needed size */
  int initValue = -1;
  while ( write(fd, &initValue, sizeof(initValue)) != sizeof(initValue) )
    continue;

  if (fork())
    writer(fd);
  else
    reader(fd);
  return 0;
}

void reader(int fd) {
  int *sharedMemory;
  volatile int val;
  int i;
  sharedMemory = mmap(0, sizeof(int), PROT_READ, MAP_SHARED, fd, 0);
  if (sharedMemory == MAP_FAILED) {
    perror("mmap");
    exit(1);
  }
  for (i = -1; ; ) {
    val = *sharedMemory;
    if (val > i) {
      i = *sharedMemory;
      printf("%d ", i);
      fflush(stdout);
    }
    sleep(1);
  }
}

void writer(int fd) {
  int *sharedMemory;
  int i;
  sharedMemory = mmap(0, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
  if (sharedMemory == MAP_FAILED) {
    perror("mmap");
    exit(1);
  }
  for (i = 0; ; i++) {
    *sharedMemory = i;
    sleep(2);
  }
}