File: sysv-msg.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 (89 lines) | stat: -rw-r--r-- 1,489 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
// msgrcv, msgsnd require _XOPEN_SOURCE
#define _XOPEN_SOURCE
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define SIZE 1024

struct my_msgbuf {
               long mtype;
               long val;
               char buf[1024];
           };

void msg_snd(int msqid, int i)
{
  struct my_msgbuf buf;
  buf.mtype = i;
  buf.val = i;
  if (msgsnd(msqid, (const void*)&buf, sizeof (long), 0) == -1) {
    perror("msgsnd failed");
    fflush(stdout);
    sleep(1);
    exit(1);
  }
}

void msg_rcv(int msqid, int i)
{
  struct my_msgbuf buf;
  buf.mtype = 0;
  buf.val = 0;
  if (msgrcv(msqid, (void*)&buf, sizeof (buf), i, 0) == -1) {
    perror("msgrcv failed");
    fflush(stdout);
    sleep(1);
    exit(1);
  }
}

void parent(int msqid)
{
  int i = 1;
  for (i = 1; i < 32000; i += 2) {
    printf("Server: %d\n", i);
    fflush(stdout);
    msg_snd(msqid, i);
    msg_rcv(msqid, i+1);
    sleep(1);
  }
  exit(0);
}

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

int main(int argc, char **argv)
{
  int msgid;

  msgid = msgget((key_t) 9977, IPC_CREAT | 0666);
  if (msgid == -1) {
    perror("semget failed");
    exit(1);
  }

  if (fork() == 0) {
    child(msgid);
  } else {
    parent(msgid);
  }
  return 0;
}