home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / unix / internal / 1978 < prev    next >
Encoding:
Text File  |  1992-11-21  |  2.2 KB  |  83 lines

  1. Newsgroups: comp.unix.internals
  2. Path: sparky!uunet!ulowell!img.ulowell.edu!aorenste
  3. From: aorenste@cs.ulowell.edu (Aaron Orenstein)
  4. Subject: Re: printf() & fork() ......
  5. Message-ID: <By3Gp5.DsK@ulowell.ulowell.edu>
  6. Sender: usenet@ulowell.ulowell.edu (News manager - ulowell)
  7. Organization: Interactive Media Group - University of Massachusetts at Lowell
  8. References:  <1992Nov19.133035.172@ccsun7.csie.nctu.edu.tw>
  9. Date: Sun, 22 Nov 1992 01:41:29 GMT
  10. Lines: 71
  11.  
  12. In article <1992Nov19.133035.172@ccsun7.csie.nctu.edu.tw>, mchuang@csie.nctu.edu.tw (Ming-Chuan Huang) writes:
  13. -> Hello:
  14. -> 
  15. -> #include <stdio.h>
  16. -> 
  17. -> program 1:
  18. -> 
  19. -> void main()
  20. -> {
  21. ->     printf("Hello ");
  22. ->     if (fork() == 0)
  23. ->         printf("world\n");
  24. -> }
  25. -> 
  26. -> result:
  27. -> Hello Hello world
  28. -> 
  29. -> program 2:
  30. -> 
  31. -> void main()
  32. -> {
  33. ->     printf("Hello \n");
  34. ->     if (fork() == 0)
  35. ->         printf("world\n");
  36. -> }
  37. -> 
  38. -> result:
  39. -> Hello 
  40. -> world
  41. -> 
  42. -> 
  43. -> is there anybody who knows the difference between the two programs ?
  44. -> 
  45. ->                                                       mchuang
  46. ->                                      mchuang@csie.nctu.edu.tw
  47.  
  48. Your problem is that you are using buffered I/O.
  49. under unix, printf() does not actually output the information until
  50. either a newline is printed, or the output is flushed.  (Output is automatically
  51. flushed when you try to get input).  So what is happening is this:
  52.  
  53. You do a printf("Hello ") and it fills the buffer with "Hello ".  When you
  54. fork, the child gets a copy of the buffer.  The parent exits, and flushes it's buffer which outputs "Hello " on the screen.  The child, adds "world" to it's
  55. buffer and then, since you gave it a newline, it flushes the buffer.  So the
  56. child prints out "Hello world"
  57.  
  58. In the second example, the newline at the end of the first printf() is flushing
  59. the buffer so the buffer is empty when the child starts...
  60.  
  61. Your problem could be solved with the following code:
  62. void main()
  63. {
  64.   printf("Hello ");
  65.   fflush(stdout);
  66.   if(fork()==0) printf("world\n");
  67. }
  68.  
  69. result:
  70. Hello world
  71.  
  72.  
  73.  
  74.     Anything else?
  75.  
  76.     Good luck
  77.     - Aaron
  78.  
  79. -- 
  80. --------------------
  81. "The Code is free, It's the comments that cost a lot..."
  82. Aaron Orenstein    (aorenste@cs.ulowell.edu, 129.63.1.11)
  83.