File: sysv-shm2.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 (96 lines) | stat: -rw-r--r-- 1,662 bytes parent folder | download | duplicates (3)
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
// shmget() needs sysv/ipc.h, which needs )XOPEN_SOURCE
#define _XOPEN_SOURCE
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define SIZE 1024

void parent(int fd)
{
  int shmid;
  if ((shmid = shmget((key_t) 9979, SIZE, IPC_CREAT | 0666)) < 0) {
    perror("shmget");
    exit(1);
  }
  struct shmid_ds shmid_ds;
  if (shmctl(shmid, IPC_STAT, &shmid_ds) == -1) {
    perror("shmctl: shmctl failed");
    exit(1);
  }
  printf("Shmid: %d\n", shmid);

  void *addr = shmat(shmid, NULL, 0);
  if (addr == (void*) -1) {
    perror("main: shmat");
    abort();
  }
  memset(addr, 0, SIZE);

  if (write(fd, &shmid, sizeof(shmid)) != sizeof(shmid)) {
    perror("write");
    abort();
  }

  int *ptr = (int*) addr;
  int i;
  for (i = 1; i< 100000; i++) {
    printf("Server: %d\n", i);
    fflush(stdout);
    *ptr = i;
    while(*ptr != -i)
      sleep(1);
  }
  *ptr = 0;
  exit(0);
}

void child(int fd)
{
  int shmid;
  if (read(fd, &shmid, sizeof(shmid)) != sizeof(shmid)) {
    perror("write");
    abort();
  }

  void *addr = shmat(shmid, NULL, 0);
  if (addr == (void*) -1) {
    perror("Child: shmat");
    abort();
  }

  int *ptr = (int*) addr;
  sleep(2);
  int val;
  while((val = *ptr) != 0) {
    int i = *ptr;
    if (i>0) {
      printf("Client: %d\n", i);
      fflush(stdout);
      *ptr = -i;
    } else {
      sleep(1);
    }
  }
  exit(0);
}

int main(int argc, char **argv)
{
  int fds[2];
  if (pipe(fds) == -1) {
    perror("pipe");
    exit(1);
  }

  if (fork() == 0) {
    child(fds[0]);
  } else {
    parent(fds[1]);
  }
  return 0;
}