Alternating Between Parent and Child -Pipes

Hi, I need to write a program that alternates between parent and child, which the child printing first. I need to output Parent or Child, the pid, and a random Number. It compiles fine, but nothing outputs. Any help?
Thank you



#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;


int main(int argc, char *argv[])
{
// Declarations
int randomNumC, randomNumP;
int numOfRandomNumbers = atoi(argv[1]);
char childWritesToPipe[1], childReadsFromPipe[1];
char parentReadsFromPipe[1], parentWritesToPipe[1];
int pipe1[2];
int pipe2[2];
char character = 'T';
int index, count;

pipe(pipe1); // Creating my pipe
pipe(pipe2);

int pid = fork(); // Creating child process

srand(numOfRandomNumbers); // Getting seed


// For loop that will go through numOfRandomNumbers < 20
for(int i = 0; i < numOfRandomNumbers; i++)
{

if(pid < 0) // if pid is less then zero, there was an error
exit(1);

if(pid == 0)
{
srand(randomNumC); // Getting a different seed for Child Random Numbers
randomNumC = rand(); // Generating random number

close(pipe2[1]);
count = read(pipe2[0], childReadsFromPipe, 3);
for(index = 0; index < count; index++)
{
char character = childReadsFromPipe[index];
if(character == 'T')
{
cout << "Child " << getpid() << " " << randomNumC << endl;
}
}
close(pipe2[0]);

cout << "Child "<<getpid() << " " << randomNumC << endl;
childWritesToPipe[0] = character;
close(pipe1[0]); // Closing off read, so child can write
write(pipe1[1], childWritesToPipe, strlen(childWritesToPipe));
close(pipe1[1]); // Closing write off
}

else{
srand(randomNumP); // Getting different seed for Parent
randomNumP = rand(); // Generating random number

close(pipe1[1]); // Closing of write, so Parent can read from Pipe
count = read(pipe1[0], parentReadsFromPipe, 3);
for(index = 0; index < count; index++)
{
char character = parentReadsFromPipe[index];
if(character == 'T'){
cout << "Parent " << getpid() << " " << randomNumP << endl;
}
}
close(pipe1[0]); // Closing read off

parentWritesToPipe[0] = character;
close(pipe2[0]);
write(pipe2[1], parentWritesToPipe, strlen(parentWritesToPipe));
close(pipe2[1]);
}
}
}
Last edited on
Calling srand() in a loop? You only need to call it once per process.

It's not clear what you're trying to do. Are you creating one child that prints 20 numbers, or are you creating 20 children that each print 1 number?
Registered users can post here. Sign in or register to post.