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
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
1. Your process may not output anything because both, parent and child at first will await messages from each other. A typical deadlock! Each one is waiting on the the other one.
2. You may also run in trouble with your array and string handlings.
2.1. count = read(pipe2[0], childReadsFromPipe, 3); reads up to 3 characters - but your buffer may take only one character. --> buffer overflow if more than one character are read from pipe2.
2.2. write(pipe2[1], parentWritesToPipe, strlen(parentWritesToPipe)); may write an undefined number of characters to pipe2 because parentWritesToPipe is a string of size one containing a non-Nul character and which cannot be Nul-terminated due to its size. So strlen(3) will result in an undefined return value.
2.3. Your index-loops will access undefined array elements if index is of any value other than 0.
2.4...
3. Finally each process closes its pipes entirely on each loop iteration. In some cases, like the writing end of pipe2 of the child process, this should only be executed once. While in other cases you should never close the pipes end because you may need it later on during the next loop iteration.