473,397 Members | 2,116 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

fork problem

Hi,
i thied the following code..
# include<stdio.h>
int main()
{
int a;
printf("Hello...");
a=fork();
printf("hi\n");
return(0);
}

the o/p is as follows..
rapti:~/prg [\>] > ./a.out
Hello... hi
Hello... hi

but when i gave
# include<stdio.h>
int main()
{
int a;
printf("Hello...\n"); // mark the \n here
a=fork();
printf("hi\n");
return(0);
}

the o/p became ..
rapti:~/prg [\>] > ./a.out
Hello...
hi
hi

can any one tell me how that \n is affecting?
and insted of the printf statement if i put some thing else.. that is
not getting evaluated two times...

please help me out...
regard
Mishra

Nov 15 '05 #1
16 5781
mishra wrote:
Hi,
i thied the following code..
# include<stdio.h>
int main()
{
int a;
printf("Hello...");
a=fork();
printf("hi\n");
return(0);
}

the o/p is as follows..
rapti:~/prg [\>] > ./a.out
Hello... hi
Hello... hi

but when i gave
# include<stdio.h>
int main()
{
int a;
printf("Hello...\n"); // mark the \n here
a=fork();
printf("hi\n");
return(0);
}

the o/p became ..
rapti:~/prg [\>] > ./a.out
Hello...
hi
hi

can any one tell me how that \n is affecting?
and insted of the printf statement if i put some thing else.. that is
not getting evaluated two times...
Looks like printf is buffering data until it gets a newline. As you fork
the original process the data for printf is also copied to the new
context, and so you see the data appear twice.
If you would change this you could try using unbuffered output.

Kind regards,
Johan

--
o o o o o o o . . . _____J_o_h_a_n___B_o_r_k_h_u_i_s___
o _____ || http://www.borkhuis.com |
.][__n_n_|DD[ ====_____ | jo***@borksoft.xs4all.nl |(________|__|_[_________]_|________________________________|

_/oo OOOOO oo` ooo ooo 'o!o!o o!o!o`
== VxWorks-page: http://www.xs4all.nl/~borkhuis/vxworks/vxworks.html ==
Nov 15 '05 #2
Ok,

If remember correctly (I', sure you'll let me know if not!):

'\n' causes the stdout buffer to be flushed, i.e. as soon as '\n' is
parsed the contents will, in this case, be displayed on screen. In the
first example you don't flush the buffer so 'Hello' will still be in
the buffer waiting to be outputted. fork () returns twice, once as the
parent process and once as the child process. The child process's
memory will be a copy of the parent process's memory (i.e. both
processes will have the same data in memory), so a copy of stdout's
buffer (which contains "Hello") will exist for both processes. When
you then go on to send "hi\n" to stdout the buffer is flushed causing
"Hello" to be displayed by both the parent and the child.

In order to better understand how fork () works you should be checking
it's return value (remembering that it returns twice) so that you can
print whether you are in the parent or the child.

Nick

Nov 15 '05 #3
mishra wrote:
Hi,
i thied the following code..
# include<stdio.h>
int main()
{
int a;
printf("Hello...");
a=fork();
printf("hi\n");
return(0);
}

the o/p is as follows..
rapti:~/prg [\>] > ./a.out
Hello... hi
Hello... hi

but when i gave
# include<stdio.h>
int main()
{
int a;
printf("Hello...\n"); // mark the \n here
a=fork();
printf("hi\n");
return(0);
}

the o/p became ..
rapti:~/prg [\>] > ./a.out
Hello...
hi
hi

can any one tell me how that \n is affecting?
and insted of the printf statement if i put some thing else.. that is
not getting evaluated two times...

please help me out...
regard
Mishra


This is my first post here, but I think I can help there. This strange
behaviour is caused because of the way that stdout behaves. Stdout is
line buffered, wich means that when you write to it, in truth you're
writting to a buffer that doesn't get "flushed" until a new line
character is written to the buffer.

In your first example, you write to stdout, but don't place any new
line character, so the actual write to console is delayed. Then you
make a fork, wich creates a copy of the process, including the buffer
to stdout. When you make the second printf, the buffer is flushed, so
both processes write the same to stdout.

In the second example, since there is a new line character in the first
printf, the buffer has been flushed, and so both processes after the
fork have an empty buffer to stdout.

So to summarize, the first printf is only executed once, as would be
any sentence that you could place before the fork. But it's effects are
replicated by the line buffering of stdout.

Hope that helped.

Nov 15 '05 #4
# This is my first post here, but I think I can help there. This strange
# behaviour is caused because of the way that stdout behaves. Stdout is
# line buffered, wich means that when you write to it, in truth you're

In this case, it is almost certainly line bufferred, but that does not
have to be generally true of stdout. To force the bufferring behaviour,
use the setvbuf function.

As a general rule, force stdio buffer flushes of all writable FILEs
before forking. You can also use fflush for this.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
No pleasure, no rapture, no exquisite sin greater than central air.
Nov 15 '05 #5
"mishra" <mi******@gmail.com> writes:
i thied the following code..
# include<stdio.h>
int main()
{
int a;
printf("Hello...");
a=fork();
printf("hi\n");
return(0);
}

the o/p is as follows..
rapti:~/prg [\>] > ./a.out
Hello... hi
Hello... hi

[snip]

There is no fork() function in standard C. Try comp.unix.programmer
(where they'll tell you, among other things, that you should #include
the proper system-specific header before using fork().)

If you invoked your compiler properly, it should warn you that fork()
is undeclared. If you're using gcc, try "gcc -ansi -pedantic -W -Wall";
change "-ansi" to "-std=c99" if you want to take advantage gcc's
incomplete C99 support. If you're using a compiler other than gcc,
check its documentation.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #6
On 19 Jul 2005 05:23:58 -0700, "Antonio" <an*****@gmail.com> wrote in
comp.lang.c:
mishra wrote:
Hi,
i thied the following code..
# include<stdio.h>
int main()
{
int a;
printf("Hello...");
a=fork();
printf("hi\n");
return(0);
}

the o/p is as follows..
rapti:~/prg [\>] > ./a.out
Hello... hi
Hello... hi

but when i gave
# include<stdio.h>
int main()
{
int a;
printf("Hello...\n"); // mark the \n here
a=fork();
printf("hi\n");
return(0);
}

the o/p became ..
rapti:~/prg [\>] > ./a.out
Hello...
hi
hi

can any one tell me how that \n is affecting?
and insted of the printf statement if i put some thing else.. that is
not getting evaluated two times...

please help me out...
regard
Mishra


This is my first post here, but I think I can help there.


Since it's your first post here, I'll point this out:

The question is off-topic and any attempts to answer it in detail are
off-topic. The topic of this newsgroup is the C language, which is
specifically and completely defined originally by the two editions of
K&R, then, since 1989, by various ANSI/ISO International Standards.

fork() is not part of the C language or its libraries. It is a
non-standard (from the point of the language and this newsgroup)
extension provided by some particular compiler and operating system
combinations.

The UNIX API does not define the C language. The Windows API does not
define the C language.

In cases like this, the only appropriate reply is to redirect the
poster to a group where his question is topical, if one knows of one.
In this case news:comp.unix.programmer would be a good choice.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #7
Jack Klein <ja*******@spamcop.net> wrote:

# The question is off-topic and any attempts to answer it in detail are

It is most definitely on-topic unless you think setbuffer, setvbuf,
printf, stdout, and _everything_ else in <stdio.h> is off-topic.
The question is about how does stdio bufferring work, not how does
fork work. A similar issue would show up if the program aborts and
appears to lose part of the output: until you know some output can
be bufferred and unknown to the operating system, you won't understand
what setvbuf refers to.

# fork() is not part of the C language or its libraries. It is a

As usual, two mistakes: "C language" is not ANSI C. Second, you see
"fork" and your knee jerks without pausing to understand the true
problem, which is how ANSI C file bufferring and interact with program
execution.

# The UNIX API does not define the C language. The Windows API does not
# define the C language.

ANSI <stdio.h> does not define the language.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
I have no respect for people with no shopping agenda.
Nov 15 '05 #8
In article <11*************@corp.supernews.com>,
SM Ryan <wy*****@tango-sierra-oscar-foxtrot-tango.fake.org> wrote:
....
ANSI <stdio.h> does not define the language.


It should be clear by now that Jack Klein defines the language.

Nov 15 '05 #9
SM Ryan wrote:
Jack Klein <ja*******@spamcop.net> wrote:

# The question is off-topic and any attempts to answer it in detail are

It is most definitely on-topic unless you think setbuffer, setvbuf,
printf, stdout, and _everything_ else in <stdio.h> is off-topic.
The question is about how does stdio bufferring work, not how does
fork work. A similar issue would show up if the program aborts and
appears to lose part of the output: until you know some output can
be bufferred and unknown to the operating system, you won't understand
what setvbuf refers to.

# fork() is not part of the C language or its libraries. It is a

As usual, two mistakes: "C language" is not ANSI C.
It is in this group, but as usual you still can't seem to comprehend
this.
Second, you see "fork" and your knee jerks without pausing to understand the > true problem, which is how ANSI C file bufferring and interact with program
execution.


The use of fork() plays a large part in the behavior being discussed
and a group like comp.unix.programmer would be a much more appropriate
place for this post. Jack was completely correct in what he said and
he couldn't have been more helpful or polite with his reply.

Robert Gamble

Nov 15 '05 #10
Kenny McCormack wrote:
SM Ryan <wy*****@tango-sierra-oscar-foxtrot-tango.fake.org> wrote:
...
ANSI <stdio.h> does not define the language.


It should be clear by now that Jack Klein defines the language.


You neglected to quote Jacks informative paragraph, which follows:
The question is off-topic and any attempts to answer it in detail
are off-topic. The topic of this newsgroup is the C language,
which is specifically and completely defined originally by the
two editions of K&R, then, since 1989, by various ANSI/ISO
International Standards.


--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 15 '05 #11
Robert Gamble wrote:
SM Ryan wrote:
As usual, two mistakes: "C language" is not ANSI C.


It is in this group, but as usual you still can't seem to comprehend
this.


<flame>
Then this group should be renamed to something along the lines of
comp.lang.c.ansi or comp.lang.ansic
</flame>

In case anyone doubts it, the flame was intended to be a joke...

Nov 15 '05 #12
Robert Gamble wrote:
SM Ryan wrote:
Jack Klein <ja*******@spamcop.net> wrote:
.... snip ...
# fork() is not part of the C language or its libraries. It is a

As usual, two mistakes: "C language" is not ANSI C.


It is in this group, but as usual you still can't seem to
comprehend this.
Second, you see "fork" and your knee jerks without pausing to
understand the true problem, which is how ANSI C file bufferring
and interact with program execution.


The use of fork() plays a large part in the behavior being discussed
and a group like comp.unix.programmer would be a much more appropriate
place for this post. Jack was completely correct in what he said and
he couldn't have been more helpful or polite with his reply.


As contrasted to Ryans continuous childish attempts to foul normal
newsreaders by insisting on his non-standard quote mark. It is
best to treat him as a pure troll, and PLONK him. This reduces the
annoyance factor and thence the blood pressure.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 15 '05 #13
Antonio wrote:
Robert Gamble wrote:
SM Ryan wrote:

As usual, two mistakes: "C language" is not ANSI C.


It is in this group, but as usual you still can't seem to
comprehend this.


<flame>
Then this group should be renamed to something along the lines
of comp.lang.c.ansi or comp.lang.ansic
</flame>

In case anyone doubts it, the flame was intended to be a joke...


Unfortunately there are those among us who would take it
seriously. They are often the same people that flout other useful
standards for no reason other than to annoy. We who restrict the
definition have at least 6 references available:

K&R I
K&R II
C89
C90
C95
C99

all of which can be fairly readily found, and all of which build on
previous work. Most of these have, at one time or another, been
stamped as "THE STANDARD" by national and international
organizations. Before recommending anything else, be sure it is
equally accepted and applicable. For example Posix is an OS
standard, not a language standard. Many systems can use the C
language that can never even approach the Posix standard.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 15 '05 #14
"Robert Gamble" <rg*******@gmail.com> wrote:

# The use of fork() plays a large part in the behavior being discussed

Your knee is jerking too. fork demonstrates the problem in this case,
but the underlying issue is not fork, but has stdio bufferring works.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
You hate people.
But I love gatherings. Isn't it ironic.
Nov 15 '05 #15
# You neglected to quote Jacks informative paragraph, which follows:
#
# >>> which is specifically and completely defined originally by the
# >>> two editions of K&R, then, since 1989, by various ANSI/ISO

Maybe you should re-read K&R 1978 pp 158-177 (chapter 8).

--
SM Ryan http://www.rawbw.com/~wyrmwif/
This is one wacky game show.
Nov 15 '05 #16
On Thu, 21 Jul 2005 05:13:48 -0000, SM Ryan
<wy*****@tango-sierra-oscar-foxtrot-tango.fake.org> wrote:
# You neglected to quote Jacks informative paragraph, which follows:
#
# >>> which is specifically and completely defined originally by the
# >>> two editions of K&R, then, since 1989, by various ANSI/ISO

Maybe you should re-read K&R 1978 pp 158-177 (chapter 8).


You mean the one that says this chapter applies only to Unix.
<<Remove the del for email>>
Nov 15 '05 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Gregory Starck | last post by:
Hello, I'm having what seems to be a deadlock in syslog with the code (wich comes from a project I'm working on, but I've reduced the test case to its minimum) I put at the end of this messsage....
1
by: Alexander N. Spitzer | last post by:
I am trying to write a program that will fork a process, and execute the given task... the catch is that if it runs too long, I want to clean it up. this seemed pretty straight forward with a...
27
by: steve | last post by:
I was given the following code, and asked what the possible outputs could be. We're learning about processes and forking. int value; int main(){ int pid, number = 1; value = 2; pid = fork();...
4
by: rh0dium | last post by:
Hi all, I have a problem with putting a job in the background. Here is my (ugly) script which I am having problems getting to background. There are threads about doing python script.py & ...
1
by: vduber6er | last post by:
Hi I want to have a wait page while the rest of the cgi does its process, but it seems like the wait page waits till everything is complete and never appears. I've tried forking twice already as...
3
by: thrillseekersforever | last post by:
The questions(A&B) are to fine no# of process running from the below codes. However, I couldn't decipher the solution. Will someone please throw some light on this? Thanks a lot!! A] void...
4
by: rohitsagar | last post by:
I want to do fork from a program Code is very simple, below is the code, it just execute a executable called a.exe, I want to run a.exe 600 times. #include<stdio.h> #include<stdlib.h> void...
3
by: CMorgan | last post by:
Hi everybody, I am experiencing an annoying problem with fork() and execv(). In my program I need to launch the "pppd" from a thread, so, I create a new process with fork and then in the child...
1
by: 3srt | last post by:
Hello, I created a simple 'server' script that will accept input from a cgi script. The server will handle multiple connections on the same port, also. In a nut shell, this 'server' script will...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.