I'm trying to write code that creates N processes 1, 2, 3, 4, ..., N for
UNIX (using fork()), where N is given by the user. The
processes can be created in any order.
Each process must print indefinitely the order in which
was created, its process id, as well as its serial number
message it prints.
Process messages must be printed alternately, in order
in which the processes were created.
Only using pipes() and fork() .The program will
terminates when the user types Ctrl-C
How can I synchronize my processes properly?
**Here is my code : **
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main()
{
int pd[2];
int p;
int i;
int N;
int x=0;
printf("Give me the number of the processes: ");
scanf("%d", &N);
for(i=0; i<=N; i++)
p=fork();
if (p==0)
{
close(pd[1]);
for(i=0; i<N; i++)
{
pipe(pd);
printf("Proccess child %d has Process id_ %d ,message %d\n", i,getpid(),x+1);
sleep(1);
write (pd[1], &x ,sizeof(x));
read (pd[0] , &x ,sizeof(x)) ;
x++;
}
}
else
{
close(pd[0]);
for(i=0; i<N-1; i++)
sleep(1);
}
return(0);
}
This is my terminal:
How can I create multiple processes and print them out like that ex. if Ν=3, terminal output:
Process 1 has process id_1, message 1
Process 2 has process id_2, message 1
Process 3 has process id_3, message 1
Process 1 has process id_1, message 2
Process 2 has process id_2, message 2
Process 3 has process id_3, message 2
Process 1 has process id_1, message 3
Process 2 has process id_2, message 3
Process 3 has process id_3, message 3