File: shared-memory2.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 (102 lines) | stat: -rw-r--r-- 2,255 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
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
102
#include <stdio.h>
#define __USE_GNU
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#include <errno.h>


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

int main()
{
  // Most of main() copied from file2.c
  int fd;
  int rc;
  char filename[100];
  char dir1[100];
  char dir2[100];

  char *dir = getenv("DMTCP_TMPDIR");
  if (!dir) dir = getenv("TMPDIR");
  if (!dir) dir = "/tmp";
  if (sizeof(filename) < strlen(dir) + 3*sizeof("/dmtcp_file_XXXXXX")) {
    printf("Directory string too large.\n");
    return 1;
  }
  strcpy(filename, dir);
  strcat(filename, "/dmtcp_dir1_XXXXXX");
  strcpy(dir1, filename);
  strcat(filename, "/dmtcp_dir2_XXXXXX");
  strcpy(dir2, filename);
  strcat(filename, "/dmtcp_file_XXXXXX");

  // Create dir1, dir2, and filename
  if (mkdtemp(dir1) == NULL) abort();
  memcpy(dir2, dir1, strlen(dir1));      // Update new prefix
  if (mkdtemp(dir2) == NULL) abort();
  memcpy(filename, dir2, strlen(dir2));  // Update new prefix
  fd = mkstemp(filename);
  if (fd == -1)
    abort();

  fprintf(stdout, "Opened %s\n", filename);
  fprintf(stdout, "Deleting %s\n", filename);
  rc = unlink(filename);
  if (rc == -1) abort();
  fprintf(stdout, "Deleting %s\n", dir2);
  rc = rmdir(dir2);
  if (rc == -1) abort();
  fprintf(stdout, "Deleting %s\n", dir1);
  rc = rmdir(dir1);
  if (rc == -1) abort();

  /* 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;
  int i;
  sharedMemory = mmap(0, sizeof(int), PROT_READ, MAP_SHARED, fd, 0);
  if (sharedMemory == MAP_FAILED) {
    perror("mmap");
    exit(1);
  }
  for (i = -1; ; ) {
    if (*sharedMemory > 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);
  }
}