venkat said:
Hi,
i have a program like
main()
{
char a[10]= " hello";
printf("%s", a);
fork();
}
which prints twice. i have similar program ,
stdout is typically line-buffered, so the output won't be actually written
until a '\n' is printed, the buffer is full, or the stream is flushed with
fflush(stdout). Returning from (or falling off of) [1] main calls exit(),
which in turn flushes all the output streams.
<ot>Of course, if meanwhile you fork, that flushing will occur in both
processes.</ot>
In general, it is better to terminate the output with a newline, an
implementation needn't even support text files (including stdout) ending
with a partial line. Try to modify the program above with printf("%s\n",
a), or adding fflush(stdout); after the printf call. Check the difference
when when fflush is called before or after fork.
[1] In C99 falling off of main() is equivalent to returning 0, but in C99
you need to explicitly specify the return type of main. In C89 falling off
is... well... it calls exit with an indeterminate value, doesn't it? But
indeterminate values always cause UB in C89, right? So practically all
programs in K&R2 which fall off of main have UB, right? Er... I'm a little
confused...
main()
{
char a[10]= " hello";
write(1, a , sizeof a);
fork();
}
which will print only once. I am not sure whether it belongs to C or
Unix. How does the printf(buffered) works over write(unbuffer). Please
also refer pointers to it if any?
<ot>write doesn't use the stdio library, so the above doesn't apply.</ot>
BTW (that also applies to fwrite(a, 1, sizeof a, stdout)): sizeof a is the
size of the array, i.e. 10. You're printing four null characters after the
'o'. Use strlen(a), or remember the size (e.g. #define A_LEN 6), or, for
string literals, use sizeof a - 1.