[Apue] fork Function

Source: Internet
Author: User

# Include <unisth. h>

Pid_t fork (void)

The fork function is called once and returns two times. The return value of a child process is 0, and that of a parent process is the ID of the child process.

The child process and the parent process continue to execute the commands after the fork call. The child process is a copy of the parent process, and the child process obtains the data space of the parent process, heap and stack copies. Note: This is a copy of the sub-process. The Parent and Child processes do not share these buckets. Parent-Child process share body section

# Include <stdio. h> # include <sys/types. h> # include <unistd. h> int glob = 6; // global variable. In the heap, char Buf [] = "A write to stdout \ n"; int main () {int var; // local variable, pid_t PID in the stack; Var = 88; If (write (stdout_fileno, Buf, sizeof (BUF)-1 )! = Sizeof (BUF)-1) {perror ("write error");} printf ("before fork: \ n"); If (pid = fork ()) <0) {perror ("fork error");} else if (pid = 0) {glob ++; var ++;} else {sleep (2 );} printf ("pid = % d, glob = % d, Var = % d \ n", getpid (), glob, VAR); exit (0 );}

Output:

A write to stdout
Before fork:
PID = 4989, glob = 7, Var = 89
PID = 4988, glob = 6, Var = 88

Fork is used in two ways:

1. A parent process wants to copy itself so that the parent and child processes can execute different code segments at the same time.

2. A process needs to execute a different program. In this case, the child process immediately calls exec after returning from fork.

 

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.