mercredi 18 mars 2020

Ring topology using pipes and fork() in C

I am trying to develop a program where the parent process generates a random number a between 1 and 500, sends it to the first child and this child calculates the max number between a and a random number he generated and sends it to the next child that does the same until it reaches the fifth child.

So far I've came up with this but got 2 problems: the parent process does not send the number in first; the random number generated is not different for each child process and is the same every time it is generated.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>

#define CHILDS 5

int biggestInt(int a, int b)
{
    return (a > b) ? a : b;
}

int main()
{
    int p1[2], p2[2];
    int i, b, c, m, p;

    if (pipe(p1) == -1)
    {
        fprintf(stderr, "Pipe1 Failed");
        return -1;
    }

    for (i = 0; i < CHILDS; i++)
    {
        srand(time(0));
        if (pipe(p2) == -1)
        {
            fprintf(stderr, "Pipe1 Failed");
            return -1;
        }

        p = fork();
        if (p == -1)
        {
            printf("Fork Failed\n");
            exit(-1);
        }
        else if (p == 0)
        {
            close(p1[1]);
            close(p2[0]);

            b = rand() % 499 + 1;
            printf("PID: %d ---- NUM: %d ---- i = %d\n", getpid(), b, i);

            read(p1[0], &c, sizeof(int));
            m = biggestInt(b, c);
            write(p2[1], &m, sizeof(m));

            close(p1[0]);
            close(p2[1]);
            exit(m);
        }
        close(p1[0]);
        close(p1[1]);
        p1[0] = p2[0];
        p1[1] = p2[1];
    }

    close(p2[1]);

    srand(time(0));
    b = rand() % 499 + 1;
    printf("PID: %d ---- NUM: %d ---- PARENT\n", getpid(), b);
    write(p1[1], &b, sizeof(b));
    close(p1[1]);

    read(p2[0], &m, sizeof(int));
    close(p2[0]);
    printf("BIGGEST NUMBER: %d\n", m);

    return 0;
}

And this is the output:

PID: 2709 ---- NUM: 267 ---- i = 0
PID: 2710 ---- NUM: 267 ---- i = 1
PID: 2711 ---- NUM: 267 ---- i = 2
PID: 2712 ---- NUM: 267 ---- i = 3
PID: 2708 ---- NUM: 267 ---- PARENT
PID: 2713 ---- NUM: 267 ---- i = 4
BIGGEST NUMBER: 267

Any help?




Aucun commentaire:

Enregistrer un commentaire