Questions about fork Functions

Source: Internet
Author: User
For more information about fork functions-general Linux technology-Linux programming and kernel, see the following. Hello everyone!
I wrote a fork function a few days ago. The book says that fork is the function returned twice. I don't quite understand it.
Write the following code:
# Include
# Include
# Include
# Include

Int main (void)
{
Pid_t pid;

Pid = fork ();

If (pid <0)
{
Printf ("Fork Error \ n ");
Exit (1 );
}
Else if (pid = 0)
{
Printf ("Child Process is printing \ n ");
}
Else
{
Printf ("Parent Process is printing \ n ");
}

// Return EXIT_SUCCESS;
Exit (0 );
}

The debugging is as follows:
(Gdb) break main
Breakpoint 1 at 0x80483f5: file fork. c, line 10.
(Gdb) s
The program is not being run.
(Gdb) run
Starting program:/home/renwei/fork

Breakpoint 1, main () at fork. c: 10
10 pid = fork ();
(Gdb) display pid
1: pid = 3171264
(Gdb) s
Child Process is printing
12 if (pid <0)
1: pid = 29603
(Gdb) s
Parent Process is printing

Program exited normally.

The first question I want to ask is: how is the condition pid = 0 executed?
The second problem is: The book says that the child process derived from the fork function has nothing to do with the parent process. The first return of the parent process or the first return of the child process may occur. Therefore, when running this program, the displayed result may be
Child Process is printing
Parent Process is printing
It may also be
Parent Process is printing
Child Process is printing
.
But what I always see at runtime is
Child Process is printing
Parent Process is printing
This result.
Why?

Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.