File: posix-mq1.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,097 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 <sys/types.h>
#include <mqueue.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void msg_snd(mqd_t mqdes, int i)
{
  char buf[16];
  sprintf(buf, "%d", i);

  errno = 0;
  if (mq_send(mqdes, buf, strlen(buf) + 1, 0) == -1) {
    perror("mq_send failed");
    fflush(stdout);
    sleep(1);
    exit(1);
  }
}

void msg_rcv(mqd_t mqdes, int i)
{
  char buf[10000];
  errno = 0;
  if (mq_receive(mqdes, buf, sizeof(buf), NULL) == -1) {
    perror("mq_receive failed");
    fflush(stdout);
    sleep(1);
    exit(1);
  }
  if (i != atoi(buf)) {
    printf("Msg mismatch: expected: %d, got: %s\n", i, buf);
    fflush(stdout);
    sleep(1);
    exit(1);
  }
}

void parent(const char *mqname)
{
  mqd_t mqdes = mq_open(mqname, O_RDWR | O_CREAT, 0666, 0);
  mq_unlink(mqname); /* parent and child will continue to use mqname */
  if (mqdes == -1) {
    perror("mq_open() failed");
    exit(1);
  }

  struct mq_attr attr;
  mq_getattr(mqdes, &attr);

  printf("mq_flags: %ld, mq_maxmsg: %ld, mq_msgsize: %ld, mq_curmsgs: %ld\n",
         attr.mq_flags, attr.mq_maxmsg, attr.mq_msgsize, attr.mq_curmsgs);
  fflush(stdout);

  int i = 1;
  while (1) {
    printf("Server: %d\n", i);
    fflush(stdout);
    msg_snd(mqdes, i);
    sleep(1);
    i++;
  }
  exit(0);
}

void child(const char *mqname)
{
  mqd_t mqdes = mq_open(mqname, O_RDWR | O_CREAT, 0666, 0);
  // Unfortunately, DMTCP doesn't yet support unlinking in child
  // while others use it:  But this seems to work fine in the parent.
  // mq_unlink(mqname); /* parent and child will continue to use mqname */
  if (mqdes == -1) {
    perror("mq_open() failed");
    exit(1);
  }

  int i=1;
  while (1) {
    msg_rcv(mqdes, i);
    printf("Client: %d\n", i);
    fflush(stdout);
    i++;
  }
  exit(0);
}

int main(int argc, char **argv)
{
  char mqname[256];
  char *user = getenv("USER");
  sprintf(mqname, "/dmtcp-mq-%s", user == NULL ? "" : user);
  mq_unlink(mqname);
  if (fork() == 0) {
    child(mqname);
  } else {
    parent(mqname);
  }
  return 0;
}