The fork function of the Linux process

Source: Internet
Author: User
Tags function definition

Fork () function

1. Required header file:

#include <unistd.h>

#include<sys/types.h>

2. Function definition

pid_t fork (void);

pid_t is a macro definition whose essence is that int is defined in #include<sys/types.h>

Return value: If successful call returns two values, the child process returns 0, the parent process returns the child process ID;

Otherwise, an error is returned-1

3. Function Description:

An existing process can call the fork function to create a new process. A new process created by Fork is called a subprocess (child process). The fork function is called once but returns two times. The only difference of two returns is that the child process ID is returned in the parent process with a value of 0.

A child process is a copy of the parent process that obtains a copy of the parent process's data space, heap, stack, and so on. There is only a code snippet for shared storage between parent and child processes.

4. Code

  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <errno.h>
  6. int main ()
  7. {
  8. pid_t pid; /*pid Process ID number * /
  9. Pid=fork (); / * Create a new process * /
  10. if (pid==0)/ * Returns 0 as child process * /
  11. {
  12. printf ("Return pid is%d\n", PID);
  13. printf ("This is son process! PID is:%d\n ", Getpid ());
  14. }
  15. Else if (pid>0)/* Returns greater than 0 for the parent process * /
  16. {
  17. printf ("Return pid is%d\n", PID);
  18. printf ("This is the parent process! PID is:%d\n ", Getpid ());
  19. Waitpid (pid,null,0);/* Wait for the child process to exit */
  20. }
  21. Else
  22. {
  23. Perror ("fork () error!");
  24. Exit
  25. }
  26. }

5. Output

The fork function of the Linux process

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.