fork question using c lang, on linux

Hi I am new to this form and I was wondering If somebody can help me with a question I have and here it is:

Write a C program to create 20 child processes for only one parent process.
The output should include:-
A- Each child process print the child number (simple counter), child pid and the parent pid.
B- The parent process prints its pid and the list of its 20 children pids (only once after all children processes get terminated properly).
note: Make sure no zombie processes are active

I wrote a c program but I don't understand why I get the output in this way (shouldn't each child have a different pid):

My program:

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

int main()
{

int a, b=0;

pid_t pid, parent;

parent=pid=getpid();

printf("The parent pid=%d\n",parent);

for (a=0;a<20;a++)
{

if (pid==parent)
pid=fork();

if (pid<0)
{
printf("Fork Error\n");
exit(1);
}
else if (pid==0)
{
printf("Parent pid=%d & child %d has pid=%d\n",getppid(),++b,getpid());

}
else
{
wait();

}


}


return 0;

}

-------------------------
The output is as follows:

The parent pid=6010
Parent pid=6010 & child 1 has pid=6011
Parent pid=6010 & child 2 has pid=6011
Parent pid=6010 & child 3 has pid=6011
Parent pid=6010 & child 4 has pid=6011
Parent pid=6010 & child 5 has pid=6011
Parent pid=6010 & child 6 has pid=6011
Parent pid=6010 & child 7 has pid=6011
Parent pid=6010 & child 8 has pid=6011
Parent pid=6010 & child 9 has pid=6011
Parent pid=6010 & child 10 has pid=6011
Parent pid=6010 & child 11 has pid=6011
Parent pid=6010 & child 12 has pid=6011
Parent pid=6010 & child 13 has pid=6011
Parent pid=6010 & child 14 has pid=6011
Parent pid=6010 & child 15 has pid=6011
Parent pid=6010 & child 16 has pid=6011
Parent pid=6010 & child 17 has pid=6011
Parent pid=6010 & child 18 has pid=6011
Parent pid=6010 & child 19 has pid=6011
Parent pid=6010 & child 20 has pid=6011
Last edited on
You are probably using NPTL (New Posix Threads Library) as opposed to the
older linux_threads library.

man gettid

and use that in the child.
Topic archived. No new replies allowed.