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

int main ()
  pid_t child_pid;

  child_pid = fork ();
  // parent process
  if (child_pid > 0) {
    printf("\n(parent): Parent's PID : %d\n",getpid());
    sleep (10);
    printf("\n(parent): Parent exits\n");
    /*int returnStatus;
    waitpid(child_pid, &returnStatus, 0);
    if (returnStatus == 0)  // Verify child process is terminated.
       printf("The child process terminated normally.");
  // child process
  else {
    printf("\n(child): Child's PID : %d\n",getpid());
    printf("\n(child): Child's Parent ID : %d\n",getppid());
    printf("\n(child): Child exits and becomes and zombie while parent 
    exit (0);
  return 0;

This is what I have so far using Vim under Unix. How do I edit modify this piece so that when the parent creates the child, it exits before the child is completed, in which it turns into an orphan; then it gets re-parented and the child exits?

I know I'm supposed to use sleep(value) to delay the processes, but I'm unsure and confused as to what I'm delaying so that the orphan can be re-parented after the initial parents leaves.

  • If a child's parent terminates before the child terminates, by default the child automatically gets reparented to init. – Andy Dalton Feb 13 '18 at 20:17

sleep is a kluge that may not work if the system is busy or otherwise may require a needlessly long delay. A better approach is to communicate between the parent and child such that the child blocks until the parent responds or in this case goes away. This can be done with a pipe and a blocking read in the child process that blocks until the parent (some time later...) does go away.

#include <err.h>
#include <errno.h>
#include <unistd.h>

int main(void)
    char ch;
    int fd[2];
    pid_t pid;
    ssize_t ret;


    pid = fork();
    if (pid < 0) {
        err(1, "fork failed");
    } else if (pid == 0) { /* child */
        warnx("child  %d start", getpid());
        // block until parent goes away
        ret = read(fd[0], &ch, 1);
        warnx("child  %d parent gone", getpid());
    } else { /* parent */
        // simulate system being slow
    return 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.