fork() and wait()

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Dec 2006
Posts: 35
Reputation: rwagnes is an unknown quantity at this point 
Solved Threads: 0
rwagnes's Avatar
rwagnes rwagnes is offline Offline
Light Poster

fork() and wait()

 
0
  #1
Mar 25th, 2007
I am supposed to create a chain of N processes, where N is the command line parameter. Each process creates a child process, prints out its own PID and its parent's PID, and then waits for its child to terminate by calling the wait() function.

Here is my code:
  1. #include <stdio.h>
  2. int main(int argc, char *argv[])
  3. {
  4.  
  5. int number = atoi(argv[1]);
  6. int i;
  7. int pid;
  8.  
  9. for (i=0; i<number-1; i++)
  10. {
  11.  
  12. pid=fork();
  13. if (pid==0)
  14. wait();
  15.  
  16. else
  17. {
  18. printf("I am the child\n");
  19. printf("my pid=%d\n", getpid());
  20. printf("and my parent pid=%d\n", getppid());
  21. }
  22.  
  23. }
  24. }
Any ideas why it's not working properly?

Example output:

[balhoffe1@gator labfork]$ ./lab2 4
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6381
and my parent pid=5670
I am the child
my pid=6382
and my parent pid=6381
I am the child
my pid=6381
and my parent pid=5670
[balhoffe1@gator labfork]$ I am the child
I am the child
my pid=6384
and my parent pid=1
my pid=6382
and my parent pid=1
I am the child
my pid=6383
and my parent pid=1
Last edited by ~s.o.s~; Mar 25th, 2007 at 1:50 pm. Reason: Added code tags, learn to use them.
Reply With Quote Quick reply to this message  
Join Date: Dec 2005
Posts: 5,850
Reputation: Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute 
Solved Threads: 749
Team Colleague
Salem's Avatar
Salem Salem is offline Offline
Void main'ers are DOOMed

Re: fork() and wait()

 
0
  #2
Mar 25th, 2007
# if (pid==0)
# wait();
fork() returns 0 in the child, not the parent.

Your if/else is the wrong way round.
Reply With Quote Quick reply to this message  
Join Date: Dec 2006
Posts: 35
Reputation: rwagnes is an unknown quantity at this point 
Solved Threads: 0
rwagnes's Avatar
rwagnes rwagnes is offline Offline
Light Poster

Re: fork() and wait()

 
0
  #3
Mar 25th, 2007
thanks! that helped alot.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC