Robert said:
I don't understand why this code is doing what its doing can someone
explain? I would think that every 1 second the word child gets printed to
the screen.... but what happens is all 10 get printed at once!!!??? why does
it do this?
thanks
#include <iostream>
#include <stdlib.h>
Or you could:
Platform specific header. Two of my platforms don't have this.
using namespace std;
int main()
{
pid_t mypid;
This is declaring a variable to hold a process ID (identifier).
Many operating systems associate identifiers with processes,
whether they be threads, or whole processes. See the manuals
about your operating system.
This functions creates another process, "forking" the current
process. The function returns the ID of the new process. At
least that seems to be common operating systems theory.
But then, the fork function could return an error value
instead. One must consult the Holy Words of their operating
system.
Execute the following code 10 times.
{
cout<<"child";
sleep(1);
The common understanding of a "sleep" function is to put
your process to sleep. This means that it is not consuming
processor resources. Many operating systems use either a
time limit for the sleep or an event. For example, one
might want to suspend their program until a user presses
a key or until a response is received from a hardware device.
Consult the Holy Words of your operating system for more
information on the sleep function.
The above loop will print "child", sleep, print "child",
and etc., for 10 iterations. The output will be:
childchildchildchildchildchildchildchildchildchild
One might not see the output since the stream is not
flushed, but one has to ask the operating system if
it flushes the stream after a program terminates (or
just before).
This statement returns execution to whatever called
the main() function, which is usually the operating
system. The value of one indicates there was a failure
executing the system. A returned value of zero or
EXIT_SUCCESS would be returned upon successful execution.
This would be a debugging output indicating that
execution is in the parent task.
To get a better grip on this stuff, read up on multi-
tasking and multiprocessing. And if you really want,
read up on mult-threading. Use these keywords on
your favorite web search engine. These concepts
are off-topic in this newsgroup.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library