well,
i just changed from wait to waitpid() and there has been a lot of improvement.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
int main()
{
int x,i=0,pid,pid2,status,r;
system("clear");
for(x=0;x<3;x++)
{
pid=-1;pid2=-1;
if((pid=fork()) == 0) //child process- the countdown timer
{
pid=getpid();
for(i=5;i>0;i--) //start a 5 sec countdown
{
printf("X=%d\tenter number(ppid=%d,pid=%d)",x,getppid(),getpid());
printf("\t\t\t\t\t\t\t%d\a\n",i);
sleep(1);
}
exit(111+x); //exit when 5 secs are over
}
else //parent process
{
if((pid2=fork()) == 0) //create a seperate child process for input
{
pid2=getpid();
//printf("\n\nscanf pid2=%d\n\n",pid2);
scanf("%d",&i);
kill(pid,SIGKILL); //when input is recieved kill the timer process
if(i==5) //check the user input
{
printf("\nYES i=5(pid=%d) for x=%d\n\n",getpid(),x);
}
else
{
printf("\nNO i!=5(pid=%d) for x=%d\n\n",getpid(),x);
}
exit(0);
}
r=waitpid(pid,&status); //wait for child process...timer process.
sleep(3); //take a deep breath
printf("\n\npid=%d,pid2=%d(wait status=%d,r=%d)\n\n",pid,pid2,status,r);
if((kill(pid2,SIGKILL))==0) //after the timer child process finishes ,if input process is still running...kill it
{
printf("\nNO i!=5(pid=%d) for x=%d\n\n",getpid(),x);//since the user did not enter anything within time.display this
}
}
}
printf("THE END(pid=%d\n",getpid()); //this should be executed when all other child processes are over.
return 0;
}
output:
Code:
X=0 enter number(ppid=7095,pid=7097) 5
X=0 enter number(ppid=7095,pid=7097) 4
X=0 enter number(ppid=7095,pid=7097) 3
X=0 enter number(ppid=7095,pid=7097) 2
X=0 enter number(ppid=7095,pid=7097) 1
pid=7097,pid2=7098(wait status=28416,r=7097)
NO i!=5(pid=7095) for x=0
X=1 enter number(ppid=7095,pid=7115) 5
X=1 enter number(ppid=7095,pid=7115) 4
X=1 enter number(ppid=7095,pid=7115) 3
X=1 enter number(ppid=7095,pid=7115) 2
X=1 enter number(ppid=7095,pid=7115) 1
pid=7115,pid2=7116(wait status=28672,r=7115)
NO i!=5(pid=7095) for x=1
X=2 enter number(ppid=7095,pid=7141) 5
X=2 enter number(ppid=7095,pid=7141) 4
X=2 enter number(ppid=7095,pid=7141) 3
X=2 enter number(ppid=7095,pid=7141) 2
pid=7141,pid2=7142(wait status=28672,r=0) #why is r=0 when pid=7141,in this case?
NO i!=5(pid=7095) for x=2
THE END(pid=7095
[c_d@localhost C scratchpad]$ X=2 enter number(ppid=1,pid=7141) 1 #orphaned yet again
[c_d@localhost C scratchpad]$
any ideas why the third time why return value of waitpid() was 0?