Linux Programming Study Notes (14) create process and parent-child process memory space

Source: Internet
Author: User
Document directory
  • 1.1. System
  • 1.2 popen: create a sub-process
  • 1.3 exec Functions
  • 1.4 fork
  • 6.2 memory ing and sub-process:
  • 6.3 copy of file descriptor
1. What is a process: a process is a program in execution

Program: code> resource> CPU
Process has a lot of Data Maintenance: Process status/process attributes
Maintain a tree structure for all process attributes

PS-A // all processes
PS-aue // valid process

Process status: (man PS)
D uninterruptible sleep (usually Io)
R running or runnable (on run Queue)
S interruptible sleep (waiting for an event to complete)
T stopped, either by a job control signal or because it is being traced.
W paging (not valid since the 2.6.xx kernel)
X dead (shocould never be seen)
Z defunct ("zombie") process, terminated but not reaped by its parent.
For BSD formats and when the stat keyword is used, additional characters may be
<High-priority (not nice to other users)
N low-priority (nice to other users)
L has pages locked into memory (for real-time and custom Io)
S is a session leader
L is multi-threaded (using clone_thread, like nptl pthreads do) multi-process
+ Is in the foreground process group foreground Process

Top real-time process viewing
Pstree view process tree
Kill sends signal kill-S signal process ID to process
Kill-l // view all signals
Kill-S 9 224 // close the 224 Process

2. Create process 1. The process-related creation function 1.1 System

INT system (const char * filename );
Create an independent process with independent code space
Wait until the execution of the new process is completed before system returns (blocking)

Use System to call a function (observe process ID to observe blocking)
The returned values of the new process are related to the returned values of the system.
1. the return value of any process must not exceed 255.
2. The returned values of processes in system are stored in 8-15 digits of the returned values of system.
The return value can be obtained through printf ("% d \ n", r> 8 );
3. There is a dedicated macro in Linux to get the returned state.
Wexitstatus (Status) // # include <Wait. H> # include <sys/Wait. H>

SYS. c

#include <stdio.h>#include <unistd.h>int main(){printf("%d\n",getpid());sleep(2);return 254;}sys2.c#include <stdio.h>#include <unistd.h>#include <wait.h>#include <sys/types.h>int main(){int r;printf("%d\n",getpid());r = system("./sleep");//printf("%d\n",r>>8 );printf("%d\n",WEXITSTATUS(r));}

Gcc sys. C-o sleep
GCC sys2.c
./A. Out

1.2 popen: create a sub-process

File * popen (const char * command, const char * type );

Int pclose (File * stream );

Case: Use popen to call LS-L and create a pipeline to read the output

# Include <stdio. h> # include <unistd. h> int main () {file * fp = popen ("cat file", "R"); // read the output here, you cannot directly write the file name/file * fp = popen ("ls-L", "R"); If (! FP) {perror ("popen"); return 1;} int FD = fileno (FP); int R; char Buf [1024] = {0 }; while (r = read (FD, Buf, 1023)> 0) {Buf [R] = 0; printf ("% s", Buf );} pclose (FP );}

1.3 exec Functions

Int execl (const char * path, const char * Arg ,...);
Int execlp (const char * file, const char * Arg ,...);
Int execle (const char * path, const char * Arg,
..., Char * const envp []);
Int execv (const char * path, char * const argv []);
Int execvp (const char * file, char * const argv []);

Purpose: Replace the data in the current Code space.
The function itself does not create a new process.
First parameter: replaced Program
The second parameter:
Command Line
Command line format: command name option parameter null
The end of the command line must be a Null String

Differences between execl execlp:
Execl only searches in the current path
Execlp can use the system search path (which can be found)
If none of them can be found, you can use the absolute path.

List of program command parameters pointed to by the command lock
If-1 fails to be returned

# Include <stdio. h> int main () {int r = execl ("/bin/ls", "ls", "-l", 0 ); // only the current path can be called. // int r = execlp ("ls", "ls", "-l", 0 ); // call the system path printf ("Call end % d \ n", R); Return 0 ;}
1.4 fork

Pid_t fork ()

1. Create a process
2. What is the code for the new process? The code for cloning the parent process is harsh.
And the cloned execution location
3. Do not call all fork return values in the sub-process = 0
4. The Parent and Child processes are executed simultaneously.

# Include <stdio. h> # include <unistd. h> int main () {printf ("before the process is created \ n"); int pid = fork (); // while (1) executed by the parent process) {If (pid = 0) {printf ("sub-process % d \ n", getpid ();} else {printf ("parent process % d \ n ", getpid ());}}}

3. Application Process

Use fork to implement multiple tasks (UNIX itself does not support threads)
1 Process
2 threads
3 Signal
4 asynchronous
5. Process pool and thread pool

4. process understanding

1. Relationship between parent and child Processes
Two independent processes
Mutual parent-child relationship
Use pstree to see
├ ── Gnome-terminal-termin── bash ── A. Out ── A. Out // parent-child relationship
│ Mongo── bash ── pstree
│ ─ ── Gnome-Pty-Helpe
│ Secrets-2 * [{gnome-terminal}]

2. Problem:
1. What if the parent process stops the child process first?
Sub-processes will become orphan processes, directly relying on the Root process (init)
The orphan process is harmless.

│ └ ── {NetworkManager}
Snapshot-A. Out

2 What if the child process ends the parent process first?
The child process ends first and becomes a zombie process.
BotNet features: it does not occupy memory CPU, but occupies a node on the Process Task Management tree (valuable)
In fact, zombie processes may waste resources for process quotas. Be sure to handle zombie Processes
├ ── Gnome-terminal-termin── bash ── pstree
│ Mongo── bash ── A. Out ── A. Out

3. Use wait to recycle zombie processes (blocking functions)
# Include <sys/types. h>
# Include <sys/Wait. H>
Pid_t wait (int * status );
Pid_t waitpid (pid_t PID, int * status, int options );
Wait is blocked until any process ends. Status receives the return value of the process. The returned value indicates the returned process number.
Waitpid blocking until the specified process ends

The 8-15 bits of status returned by wexitstatus (Status) parsing are the return values of processes.

4. How does the parent process know that the child process exits?
When the child process ends, it usually sends a sigchld signal to the parent process.

5. The parent process processes the signal of the child process.
# Include <signal. h>
Typedef void (* sighandler_t) (INT );
Sighandler_t signal (int signum, sighandler_t handler );
Signal Functions:
Register with the system. If the signal is received, the system stops the process and executes the handler function,
When the function execution is complete, continue the original process (Soft Interrupt)
5.1 implement processing functions
5.2 use signal to bind signals and functions

Wait is used only when the sub-process exits, because wait is a blocking function. Therefore, wait and signal are used together.

# Include <stdio. h> # include <unistd. h> # include <sys/Wait. h> # include <sys/types. h> # include <signal. h> void deal (INT s) {printf ("recycling \ n"); sleep (5); int status; wait (& status ); printf ("recycled % d \ n", wexitstatus (Status);} int main () {printf ("before Process Creation \ n "); int pid = fork (); // If (pid = 0) executed by the parent process {printf ("sub-process % d \ n", getpid ()); sleep (5); Return 88;} else {printf ("parent process % d \ n", getpid (); signal (sigchld, deal); While (1) {sleep (1); printf ("parent \ n") ;}return 0 ;}}

Zhao @ Ubuntu :~ /Unix/5 $./A. Out
Before creating a process
Parent process 2324
Sub-process 2325
88 after recycling
^ C

6. memory space of parent and child Processes

6.1 The local variable heap variables of global variables are copied by the quilt process, but they are independent from the original ones.

Note that the heap memory has been copied and needs to be manually released in each process.

The child process clones the global and local memory of the parent process, but the memory area points to different physical spaces.
Despite cloning, the memory is independent and cannot be accessed from each other.
Inter-process communication (IPC) is a big problem.

6.2 memory ing and sub-process:

Memory ing attribute determines whether the sub-process and parent process are mapped to the same physical space.
Map_shared: maps to the same physical space. (Changing the process also changes other processes)
Map_private: maps to different physical spaces.

# Include <stdio. h> # include <unistd. h> # include <sys/Mman. h> int main () {int * A = MMAP (, prot_read | prot_write, map_anonymous | map_shared,); * A = 20; int pid = fork (); // If (pid = 0) {* A = 90; printf ("parent: A = % d \ n", * a) executed by the parent process ); // 90} else {sleep (3); printf ("Child: A = % d \ n", * A); // 90 }}

Because map_shared is used, the same physical space is shot, and the changes will affect others.

If map_private is used, it can be mapped to different physical spaces.

6.3 copy of file descriptor

Each process maintains a file descriptor list.
The file descriptor is copied between parent and child processes. The same file descriptor points to the same file kernel object.
1. The file descriptor of each process must be closed.
2. Reading and Writing a file changes the position of the reading and writing pointer of the file object and affects all processes.

# Include <stdio. h> # include <unistd. h> # include <sys/Mman. h> # include <fcntl. h> int main () {int FD = open ("test.txt", o_rdwr); int pid = fork (); // If (pid = 0) executed by the parent process) {printf ("parent: \ n"); char Buf [1024] = {0}; lseek (FD, 0, seek_set); read (FD, Buf, 1023 ); printf ("% s \ n", Buf); close (FD);} else {printf ("Child: \ n"); char Buf [1024] = {0 }; lseek (FD, 0, seek_set); read (FD, Buf, 1023); printf ("% s \ n", Buf); close (FD );}}

Process data exchange is based on two methods:
Memory: ordered/disordered: MMAP
File: ordered/unordered: normal file
Kernel-based object: File/memory/queue

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: 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.