I'm trying to create a parent process with multiple child processes using fork() in C++. I tried using the code from this question to create a simple program that would have each process count upwards; the parent would print "I am process 0", the first child "I am process 1", and so on.
#include <unistd.h>
#include <stdio.h>
#include <fstream>
#include <sys/wait.h>
using namespace std;
const int PROCESSES = 5;
void Printer(int psno);
int iAmProcess = 0;
int main()
{
int pids[PROCESSES];
Printer(iAmProcess);
for (int j = 0; j < PROCESSES; j++)
{
if (pids[j] = fork() < 0)
{
perror("Error in forking.\n");
exit(EXIT_FAILURE);
}
else if (pids[j] == 0)
{
Printer(iAmProcess);
exit(0);
}
}
int status;
int pid;
int n = PROCESSES;
while (n > 0)
{
pid= wait(&status);
--n;
}
return 0;
}
void Printer(int psno)
{
printf("I am process %d\n", psno);
}
Instead of the expected output:
I am process 0
I am process 1
I am process 2
I am process 3
I am process 4
I am process 5
I get:
I am process 0
I am process 0
I am process 0
I am process 0
And then the program terminates. What am I doing wrong?