Linux Multi-Process learning

Source: Internet
Author: User
Tags sprintf stdin types of functions

1Linux Process Overviewa process is the process of executing a program, and he differs from the program in essence. The program is static, and he is an ordered collection of instructions saved on disk. process is the concept of dynamic, he is the program of the runner, contains the process of dynamic creation, scheduling and extinction, is the basic Linux scheduling unit. Process Control block (PCB) is a static description of the process, including process description information, Process control information, and resource informationtime slices: He turns the time slices in each process to get out of the process there back control right
1.1 Process identityThe OS assigns each process a unique prevalence ID, as the process's identification number (PID), and the parent process ID (ppid) The ancestors of all processes are the same process init process with ID 1by Getpid (), getppid () Gets the pid,ppid of the processExample:printf ("pid:%d ppid:%d\n", Getpid (), Getppid ());
1.2 The user ID of the process and the group ID
The process must have a user-like identity, which is the user's identity, the user's group available getuid (), Getgid (); The acquisition process also has a valid user ID and valid group ID, in the absence of the same as the real ID, can be used geteuid (), Getegid ();   When the file permission has s, the valid ID is the process owner (creator), otherwise the valid ID is the program's runner, the same as the real ID
Ps-aux View the permissions, CPU, and memory usage of all user processes
ps-ef View pid and Ppid and cmd for user actions (command line)
1.3 Status of the processexecution State, ready state, waiting state
Process structure under 1.4LInuxprocesses in Linux contain three segments: Data segments, code snippets, stack segmentsData segment: (normal data segment) global variable, Changshu (BBS data segment) is the initialized global variable and (heap) the data space allocated by Dynamic DataCode snippet: Data that holds program codeStack segment: The return address of the subroutine, the parameters of the subroutine, the local variables of the program


Process Management under 1.5LInux

process: is the smallest unit of the OS1) PS View Active process2) Ps-aux View all Processes%cpu,%mem stat status (s sleep t pause R run Z Zombie)3) ps-aux|grep ' AA ' to find the specified (AA) process4) Ps-ef can be a real parent-child relationship and CMD5) Top 20 process, dynamic change6)./my_add may have to run for a long time, press CTRL + Z can put the capital suspended, in the execution BG job ID can bring the process into the background to run for example:[1]+./my_add 1 &,& indicates that the process is running in the background. use Jods to view background tasksFG Job ID bring backstage characters to the foreground7) kill-9 process number (PID) kill the process, pkill a process name
2 creation of the processThere are four types of functions that create sub-processes under Linux: System (), fork (), exec* (), Popen ();2.1system functionSystem functions The system parentheses contain commands, which is CMDexamples are as follows:
#include <iostream> #include <stdlib.h> #include <string.h> #include <stdio.h>using namespace Std;int Main (int Argc,char *argv[]) {char cmd[1024]= ""; for (int i=1;i<argc;i++) {strcat (cmd,argv[i]); strcat (cmd, "") ;} Puts (cmd), int ans;ans=system (cmd);p rintf ("%x\n", ans);
call other executable programs with system and enter parameter inputs for example:./main./my_add where My_add calculates the sum of two numberswhere the result of the calculation is on high byte of the return value of system: ret00, so directly out of the
int main (int argc,char *argv[]) {if (argc!=2) {printf ("failed\n"); return 0;} int Left,right;char cmd[1024]= "", Char line[1024]= "", strcat (Cmd,argv[1]), strcat (cmd, ""), while (printf (">>"), scanf ("%d%d", &left,&right)) {memset (line,0,sizeof line); sprintf (line, "%s%d%d", argv[1],left,right); strcpy (cmd,line); int Ret;ret=system (cmd);p rintf ("result:%d\n", ret/256);}}
2.2fork functionThe fork function creates a new process in the existing process, the new process as a child process, the original process as the parent processThe return value of the parent process is a child process, and the return value of the child process is 0.Fork creates a child process that is fully replicating the parent process, and the buffer is also copiedboth the meta-process and the sub-capital are returned from the function fork and continue round in their respective circles, but the fork return value of the META functionis the PID of the child process, and the fork returns 0 in the child process, and 1 indicates that the creation failed
#include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h>using namespace Std;int Main (int Argc,char *argv[]) {pid_t pid;int i=3;printf ("hello\n");p id=fork (); fflush (stdout);//Copy the buffer when the son copies it. If there is no such sentence, the above hello will appear maturity if (pid>0) {printf ("parents:pid:%u,ret:%u,pp:%u\n", Getpid (), Pid,getppid ());} else if (pid==0) {//sleep (5);p rintf ("child:pid:%u,ret:%u,pp:%u\n", Getpid (), Pid,getppid ());} printf ("bye!\n");}

2.3exec functionThe EXEC function overwrites the existing process space with a program developed with the first parameter of exec, that is, after executing the EXEC family function, all the code behind him is no longer executeddetailed use method in Terminal input man execint 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[]);
int execvpe (const char *file, char *const argv[], char *const envp[]);
where path is a full pathname containing the execution file name, multiple parameters, note that the last argument must be Null,arg is the command-line argument of the executable file
int execl (const char *path, const char *arg, ...); For example:
if (Execl ("/home/yang/0820/my_exec/", "My_add", "3", "2", NULL) ==-1) {perror ("execl error");}
int EXECLP (const char *file, const char *arg, ...); For example:
if (EXECLP ("./my_add", "My_add", "fwef", "Fwe", "Fewgeraf", NULL) ==-1) {perror ("EXECLP error");}
int execv (const char *path, char *const argv[]); For example:

Char *args[10];args[0]= "My_add"; args[1]= "," args[2]= ", Args[3]=null;if (Execv ("/home/yang/0820/my_exec/my_add ", args) ==-1) {perror (" execl: ");}

2.4popen function (Supplement later)The popen function is similar to the system function, which differs from the system in that it uses pipeline operations.prototype for#include <stdio.h>

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

int Pclose (FILE *stream);

command is the full path and execution parameters of the executable file,Type Optional parameter is "R" or "W"The file stream returned by the "W" popen as a standard input stream for a new process (for example, my_add.exe), i.e. stdinThe file stream returned by the "R" Popen is stdout as the standard output stream of the new process .This means that popen only changes the standard input stream or standard output stream of the new process.popen Detailed process: Type "R", (that is, the command command execution results as the input of the current process), the caller can use the Popen function to return file* file stream pointers, it is possible to pass the common Stdio library such as Fgets, To read the output of the called function. If the type is "W" (that is, the output of the current program as input to the commend command), the calling program can send the data with Fwrite to invoke the program, and the called program can read the data on its own standard inputExample:Main program screen output:
FILE *fp;char A[1000];char b[1000];char cmd[1024]= "";p rintf ("Plseas write\n"); fgets (A,1000,stdin); sprintf (cmd, "%s%s ", argv[1],a); Fp=popen (cmd," R ");//This command cmd is the full path of the executable file fgets (B,1000,FP);p rintf ("%s\n ", b);

New Process Screen output:
FILE *fp;char A[1000];gets (a), Fp=popen (Argv[1], "w"), Fputs (A,FP);p close (FP);

3. Process Control and terminationWhen you start a child process with the fork function, the child process has its own life running independently. Orphan process : If the parent process exits before the child process, the child process becomes the orphan process (usually the parent process is responsible for releasing the memory space of the child process), which is automatically taken over by the PID 1 process (that is, init). After the orphan process exits, its cleanup work is automatically handled by the ancestor process Init Zombie Process : The child process exits, the system does not automatically clean up the working environment of the child process, there must be a parent process helper wait or waitpid function to complete the cleanup work, if the parent process does not do cleanup work, once the roll-out of the child process will become a zombie process, System performance can be affected by excessive zombie processesfunction Prototypes:#include <sys/types.h>#include <sys/wait.h>pid_t Wait (int *status);pid_t waitpid (pid_t pid,int *status,int options);The wait function randomly waits for a child process that has exited and returns the PID of the child process waitpid waiting for the PID to be developed, such as fire for-1 means waiting for all child processesThe Status parameter is an outgoing parameter that holds the exit state of the child processThe options are used to change the behavior of Waitpid, the most important of which is Wnohang, which indicates that no matter whether the child process exits immediately returnsexamples of spawned zombie processes:
#include <stdio.h> #include <stdlib.h> #include <unistd.h>main () {    pid_t pid = fork ();    if (PID = = 0)    {        exit];    }    else    {sleep (ten);    }}
examples of avoiding zombie processes:
#include <stdio.h> #include <stdlib.h> #include <unistd.h>main () {    pid_t pid = fork ();    if (PID = = 0)    {        exit];    }    else    {wait (NULL);    Null means waiting for all processes to sleep (10);//usually put sleep behind wait, or else the zombie process    }}

3.2 Termination of the process5 ways to terminate:1) Main function returns naturally2) Call the Exit Function3) Call the _exit functionCall the Abort functionaccept a signal that can cause the process to terminate CTRL + Cexit differs from _exit: Exit handles the contents of the buffer, _exit does not process the contents of the buffer

The exit and _exit functions are prototyped:

Header files for #include <stdlib.h>//exit

Header files for #include <unistd.h>//_exit

void exit (int status);

Void_exit (int status);

Status is an integer parameter that can be used to pass the process to the end of the state, 0 means normal exit, the other number indicates an error, the process is not normal end







































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.