Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a program that creates a child process using fork. **Each of the parent and the child should execute a loop, causing it to sleep for 1 second, wake up** and display its pid and say whether it is the parent or the child and also display its parent's pid.

This is what I have written so far. I'm not sure about the part in the question written in bold and if I have written it correctly in the code. Please, help. Thanks.

What I have tried:

C
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>

int main(){

  if(fork() ==0){
    printf("Child Process!\n");
    sleep(1);
  }else{
    printf("Parent Process with pid %d\n", getppid());
    sleep(1);
  }
  return 0;
}
Posted
Updated 22-Mar-21 23:00pm
v2
Comments
Rick York 23-Mar-21 1:36am    
You have not written a loop. Beyond that, I'm not sure what you want help with.

1 solution

You are close to satisfy the requirements. Try
C
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(){

  if( fork() == 0 )
  {
    for (;;)
    {
      printf("Child Process. parent process id is %u\n", getppid());
      sleep(1);
    }

  }
  else
  {
    for (;;)
    {
      printf("Parent Process.\n");
      sleep(1);
    }
  }
  return 0;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900