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
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- int main ()
- {
- pid_t pid; /*pid Process ID number * /
- Pid=fork (); / * Create a new process * /
- if (pid==0)/ * Returns 0 as child process * /
- {
- printf ("Return pid is%d\n", PID);
- printf ("This is son process! PID is:%d\n ", Getpid ());
- }
- Else if (pid>0)/* Returns greater than 0 for the parent process * /
- {
- printf ("Return pid is%d\n", PID);
- printf ("This is the parent process! PID is:%d\n ", Getpid ());
- Waitpid (pid,null,0);/* Wait for the child process to exit */
- }
- Else
- {
- Perror ("fork () error!");
- Exit
- }
- }
5. Output
The fork function of the Linux process