#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/neutrino.h>
#include <process.h>
#include <string.h>

int main(int argc, char *argv[]) {
    const char *MODULE_2_PATH = "/home/host/m2/x86/o/m2";

    int chid = ChannelCreate(0);
    printf("P1 running with chid = %d\n", chid);

    char buffer[20];
    char *strChid = itoa(chid, buffer, 10);

    int p2pid = spawnl(P_NOWAIT, MODULE_2_PATH, MODULE_2_PATH, strChid, "2", NULL);
    if (p2pid < 0)
        printf("P2 spawn error\n");

    int p3pid = spawnl(P_NOWAIT, MODULE_2_PATH, MODULE_2_PATH, strChid, "3", NULL);
    if (p3pid < 0)
        printf("P3 spawn error\n");

    int rcvid = -1;
    char msg[512];
    _msg_info info;

    int msgCounter = 0;
    while (msgCounter < 2) {
        rcvid = MsgReceive(chid, msg, sizeof(msg), &info);
        if (rcvid == -1)
            printf("P1 msg receive error\n");
        else
            printf("%s\n", msg);
        MsgReply(rcvid, 0, msg, sizeof(msg));
        msgCounter++;
    }

    printf("P1 OK\n");
    return EXIT_SUCCESS;
}
