summaryrefslogtreecommitdiff
path: root/parent.c
blob: dcce4a272573ccf7abd7f975e1d121c9e82e7d0e (plain)
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
#include <stdint.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

#include "dist.h"
#include "ipc.h"
#include "banking.h"

void parent_phase4( my_info_t *me, dist_info_t *info ) {
  Message msg;
  BalanceHistory *b_history;
  AllHistory history;

  uint8_t i;
  for( i = 1; i <= info->x; i++ ) {
    if( !receive( me, i, &msg ) ) {
      //TODO: what if s_payload_len more than s_history[i]?
      b_history = (BalanceHistory *) msg.s_payload;
      memcpy( &history.s_history[i-1], b_history, sizeof( *b_history ) );
    }
  }

  history.s_history_len = info->x;
  print_history( &history );
}

void parent_phase2( my_info_t *me, dist_info_t *info ) {
  bank_robbery( me, info->x );

  Message msg = {
    .s_header = {
      .s_magic = MESSAGE_MAGIC,
      .s_payload_len = 0,
      .s_type = STOP,
      .s_local_time = get_physical_time()
    }
  };

  send_multicast( me, &msg );
}

void parent_workflow( dist_info_t *info ) {
  Message msg;
  uint8_t i, receive_cnt;
  pid_t wpid; 
  int status;
  int ret = 0;

  my_info_t me = {
    .id = PARENT_ID,
    .dist_info = info
  };

  // PARENT PHASE 0: Close all redundant descriptors
  close_redundant_pipes( info, PARENT_ID );

  // PARENT PHASE 1: Receive all STARTED messages from all childs
  for( i = 1; i <= info->x; i++ ) {
    if( !receive( &me, i, &msg ) ) {
      if( msg.s_header.s_type != STARTED ) {
        ret = 1;
        break;
      }
    }
  }
 
  // PARENT PHASE 2: Bank robbery & send STOP for all childs 
  parent_phase2( &me, info );

  // PARENT PHASE 3: Receive all DONE messages
  for( i = 1; i <= info->x; i++ ) {
    if( !receive( &me, i, &msg ) ) {
      if( msg.s_header.s_type != DONE ) {
        ret = 1;
        break;
      }
    }
  }

  // PARENT PHASE 4: Receive all BALANCE_HISTORY and print all history
  parent_phase4( &me, info );

  // PARENT PHASE 5: Wait for the end of all processes
  receive_cnt = info->x;
  while( receive_cnt != 0 ) {
    if( (wpid = wait(&status)) > 0 ) {
      receive_cnt--;
    }
  }

  exit( ret );
}