Fork Create Process
Function prototypes are as follows
#include// must introduce a header file , you must include this header file when using the fork function, otherwise the system cannot find the fork function
pid_t fork (void); void represents no formal parameter
Parent and child processes
1. Mastering the concept, what is the parent process, what is a child process
In addition to process 0 (System-created),Linux systems are created by other processes. The process that creates a new process, the process that calls the fork function, is the parent process, and the newly created process is a child process.
2.fork functions do not require any parameters, there are three cases for the return value
1) for the parent process, The fork function returns the PID of the new child process ;
2) for sub-processes, thefork function returns 0;
3) If an error occurs, the fork function returns -1.
Create a process case (FORK.C)
#include
#include
#include
int main (void)
{
pid_t pid;
PID = fork ();
if (PID < 0)
{
printf ("Fail to fork\n");
Exit (1);
}
if (PID = = 0)
{
printf ("This was the Child,pid is:%u\n", Getpid ());
Exit (0);
}
if (PID > 0)
{
printf ("This is the parent\n");
Exit (0);
}
return 0;
}
Compile the program in the shell as follows:
GCC Fork.c-o Fork
Run the program in the shell as follows:
./fork
The result of the final output:
Run the results again as follows:
Parent-child process shared resources
1. Parent-Child process shared code snippet (readable)
When a parent process creates a child process, the child process places the data segment in the address space of the parent process. And the stack are copied, but no code snippets are copied.
2. See detailed code examples (fork_1.c)
fork_1.c
#include
#include
#include
int global; Global variables in the data segment
int main ()
{
pid_t pid;
int stack = 1; local variables in the stack
int * HEAP;
heap = (int *) malloc (sizeof (int)); in the heap
*heap = 2;
PID = fork ();
if (PID < 0)
{
printf ("Fail to fork\n");
Exit (1);
}
if (PID = = 0)
{
global++;
Stack + +;
(*heap) + +;
printf ("The Child, Data:%d, stack:%d, heap:%d\n", Global, Stack, * heap);
Exit (0);
}
Sleep (2);
printf ("The Parent, data:%d, stack:%d, heap:%d\n", Global, Stack, *heap);
return 0;
}
The results of the operation are as follows:
What happens when the fork function goes wrong
The 1.fork function returns a value of 1 which creates a failure, and there are two cases where the fork function may be faulted;
2. There are already too many processes in the system;
3. The user who called the fork function has too many processes.
original link:http://www.maiziedu.com/wiki/process/fork/
Method steps for the Linux creation process fork