Unix Programming - output of a program differs when the result of the program is directed to a file

This is Interesting: Free IT Magazines  
Home > Archive > Unix Programming > November 2005 > output of a program differs when the result of the program is directed to a file





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author output of a program differs when the result of the program is directed to a file
bdoniv@gmail.com

2005-11-26, 2:50 am

main()
{

printf("Hello\n")

if(fork()==0)
printf("world\n");

return ;
}

The result of this program when run is ::
$./a.out
Hello
world.

but when the output is directed to some other file that is
$./a.out > file

The result in the file is
Hello
world
Hello

can any one explain why an extra Hello appears ......when the output is
directed to afile .

Pascal Bourguignon

2005-11-26, 2:50 am

bdoniv@gmail.com writes:

> main()
> {
>
> printf("Hello\n")
>
> if(fork()==0)
> printf("world\n");
>
> return ;
> }
>
> The result of this program when run is ::
> $./a.out
> Hello
> world.
>
> but when the output is directed to some other file that is
> $./a.out > file
>
> The result in the file is
> Hello
> world
> Hello
>
> can any one explain why an extra Hello appears ......when the output is
> directed to afile .


The buffering behavior of your libc varies according to the output file type.
Try to insert some fflush(stdout);...


--
__Pascal Bourguignon__ http://www.informatimago.com/
Daniel C. Bastos

2005-11-26, 7:49 am

In article <1132988931.104330.96990@g44g2000cwa.googlegroups.com>,
bdoniv@gmail.com wrote:

> main()
> {
>
> printf("Hello\n")
>
> if(fork()==0)


Did you try to compile what you show here?

> printf("world\n");
>
> return ;
> }
>
> The result of this program when run is ::
> $./a.out
> Hello
> world.


Where does the ``.'' come from?

>
> but when the output is directed to some other file that is
> $./a.out > file
>
> The result in the file is
> Hello
> world
> Hello
>
> can any one explain why an extra Hello appears ......when the output is
> directed to afile .


In one way, the standard out is line-buffered, in another way the
standard out is fully buffered. A call to fork duplicates the calling
process with the exceptions of the things listed in the manual page of
the system call. Unflushed buffers are copied to the child process and
this leads to the problem you seem to experience.

How could you fix the problem?
Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com