Orphaned processes : Please explain

Rajeev Menon rajeev at hpnmdla.HP.COM
Sat Sep 15 08:03:30 AEST 1990


I am running HP-UX A.B3.10 on an HP 9000/855.

I am have a little program that creates three more processes, such that P0
the original process is parent of P1, which is parent of P2, etc. After
creating the processes, I ask each process to print out its PID and PPID
into a file called "junk". I am in no way synchronizing the processes, so
the order they write to this file is "random". But it doesn't seem random...
And sometimes it seems hard to explain. Can someone help ???

Here is the program called "fork.c"

--------------------------Cut here---------------------------------------
#include <stdio.h>
int cprocs(nprocs)
int nprocs;
{
  int i, pid;
  for ( i=0; i<nprocs; i++) {
      if ((pid = fork()) == -1)
         _exit(127);
      else if (pid)
         break;
  }
  return i;
}

main()
{
  int i, pid;
  FILE *fp; 
  if ( (fp = fopen("junk", "w")) == NULL )
     perror("Error in fopen");
  i = cprocs(3);
  fprintf( fp, "i=%d, pid = %d, ppid = %d.\n", i, getpid(), getppid());
  fclose(fp);
}
--------------------------Cut here---------------------------------------
Here is a sequence that I cannot understand :

% cc fork.c ; a.out ; cat junk
i=0, pid = 10593, ppid = 20487.
i=2, pid = 10598, ppid = 10597.
i=3, pid = 10599, ppid = 10598.
i=1, pid = 10597, ppid = 10593.
% cc fork.c ; a.out ; cat junk
i=0, pid = 10779, ppid = 20487.
i=2, pid = 10781, ppid = 10780.
% cc fork.c ; a.out ; cat junk
i=3, pid = 11122, ppid = 11121.
i=2, pid = 11121, ppid = 11120.
i=0, pid = 11119, ppid = 20487.
i=1, pid = 11120, ppid = 11119.

Sometimes (as in case 2),the file "junk" does not contain output from all 
the processes. Why ? Now I do

% a.out ; cat junk
i=0, pid = 11189, ppid = 20487.
i=1, pid = 11190, ppid = 1.
i=2, pid = 11191, ppid = 1.
i=3, pid = 11192, ppid = 1.
% a.out ; cat junk
i=2, pid = 11251, ppid = 11250.
i=3, pid = 11252, ppid = 1.
i=0, pid = 11249, ppid = 20487.
i=1, pid = 11250, ppid = 11249.

Some PPIDs show up as 1, showing that they have been orphaned, which could
be expected since I am not synchonizing the processes. But it really puzzles
me as to why this happens when I do "a.out ; cat junk" and not when I do 
"cc fork.c ; a.out ; cat junk". Can someone explain what is going on ?

Thanks

Rajeev Menon

Rajeev Menon				
Hewlett Packard Company			e-mail: rajeev at hpnmd.hp.com
1400 Fountaingrove Pkwy
Santa Rosa CA 95403



More information about the Comp.unix.questions mailing list