#include "common.h" #include "ipc.h" #include "pa1.h" #include "proc.h" #include #include #include #include #include #include #include struct settings { uint8_t proc_num; }; int settings_init(struct settings* settings, int argc, char *argv[]) { settings->proc_num = 2; int c; while (1) { int option_index = 0; static struct option long_options[] = { {"processes", required_argument, 0, 0 }, {0, 0, 0, 0 } }; c = getopt_long(argc, argv, "p:", long_options, &option_index); if (c == -1) break; switch (c) { case 'p': ; char *eptr = NULL; unsigned long val = strtoul(optarg, &eptr, 10); if (*eptr) { return 1; } if (val > MAX_PROCESS_ID) { return 1; } settings->proc_num = val; default: return 2; } } return 0; } void child_cycle(FILE *log, Process *me) { char entry[100]; size_t size = snprintf(entry, 100, log_started_fmt, me->id, getpid(), getppid()); printf("%s", entry); fprintf(log, "%s", entry); Message msg; msg.s_header.s_magic = MESSAGE_MAGIC; msg.s_header.s_payload_len = size; msg.s_header.s_type = STARTED; strncpy(msg.s_payload, entry, MAX_PAYLOAD_LEN); if (send_multicast(me, &msg)) { fprintf(stderr, "Sending multicast failed\n"); } await_all(me, msg.s_header.s_type); snprintf(entry, 100, log_received_all_started_fmt, me->id); printf("%s", entry); fprintf(log, "%s", entry); size = snprintf(entry, 100, log_done_fmt, me->id); printf("%s", entry); fprintf(log, "%s", entry); msg.s_header.s_payload_len = size; msg.s_header.s_type = DONE; strncpy(msg.s_payload, entry, MAX_PAYLOAD_LEN); send_multicast(me, &msg); await_all(me, msg.s_header.s_type); snprintf(entry, 100, log_received_all_done_fmt, me->id); printf("%s", entry); fprintf(log, "%s", entry); } void parent_cycle(Process *me) { await_all(me, STARTED); await_all(me, DONE); for (uint8_t i = 0; i < me->fildes_num - 1; ++i) { int wstatus = 0; wait(&wstatus); } } int main(int argc, char *argv[]) { struct settings settings; settings_init(&settings, argc, argv); uint8_t n = settings.proc_num; FILE *pipe_log = fopen(pipes_log, "w"); FILE *event_log = fopen(events_log, "w"); Process me; proc_init(n + 1, &me, pipe_log); fclose(pipe_log); if (me.id != PARENT_ID) { child_cycle(event_log, &me); } else { parent_cycle(&me); } proc_destruct(&me); return 0; }