Linux Multi-learning process

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

1Linux Process OverviewThe process is that once the program runs, he and the program are essentially different. The program is static, and he is instructed to collect instructions stored on disk. The process is a dynamic concept. He is the executor of the program, including the dynamic creation of the process. Scheduling and extinction, is the basic Linux scheduling units. The Process Control block (PCB) is a static descriptive narrative of the process, which contains descriptive narrative information about the process. Process Control information, and resource informationtime slices: He turns on every process to get the time slices run out after the back control from the process there
1.1 Process identityThe OS assigns a unique prevalence ID to each process. As the identification number (PID) of the process. And the parent process ID (ppid) The ancestors of all processes are the same process init process with ID 1the PID of the process is obtained by Getpid (), Getppid ( ). PpidExample:printf ("pid:%d ppid:%d\n", Getpid (), Getppid ());
1.2 The user ID of the process and the group ID
Process execution must have a user-like identity, which user is the user's identity, that is, 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 entire person of the process (creator), otherwise the valid ID is the program's executor, and the real ID is the same
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 processoperating state. Ready state. Waiting State
Process structure under 1.4LInuxthe process in Linux consists of three segments: Data segment, code snippet, stack segmentData 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, and the number of references to the subroutine. Local variables of the program


watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvew91bmd5yw5newfuzza0/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast ">
Process Management under 1.5LInux


process: is the smallest unit of the OS1) PS View Active process2) Ps-aux View all process%cpu. %mem stat status (s sleep t pauses R execution 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 The process of the top reality. Dynamic Change6)./my_add may take a very long time. Press CTRL + Z to suspend the capital. Performing a BG Job ID enables the process to be carried out in the background such as:[1]+./my_add 1 &,& indicates that the process is executing 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 functionThe system function in the system bracket is a command, that is, cmdExamples include the following:

#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);
use System to invoke other running programs and enter input parameters such as:./main./my_add My_add calculates the sum of two numbersThe result of the calculation is on the system return value high byte: 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 process that exists, and the new process acts as a child process. The original process is the parent processThe return value of the parent process is a child process. The return value of the child process is 0.Fork creates a child process that is completely 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 to circle in their respective circles. But the fork return value of the META functionis the PID of the child process. While fork in the subprocess returns 0, 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. , assuming 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 you run the Exec family function. All the code behind him is no longer running.specific usage 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 the full path name that includes the name of the running file. Multiple parameters. Note that the last parameter that follows must be Null,arg is a command-line parameter that can run the 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 run parameters of the executable file.Type Optional number of "R" or "W"The file stream returned by "W" popen as a standard input stream for new processes (such as 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 The specific process: type "R", (that is, the run result of command commands as the input result of the current process). The calling program uses the Popen function to return a file* file stream pointer. It is possible to pass a frequently used stdio library such as Fgets. To read the output of the called function.

Assuming that 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 sample on its own standard input : the 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 independently executed. Orphan process : Assuming that the parent process exits before the child process, the child process becomes the orphan process (typically the parent process is responsible for releasing the memory space of the child process), at which point it takes over the process of PID 1 (that is, init). After the orphan process exits. Its cleanup work is handled by the ancestor process Init itself Zombie Process : The child process exits, the system does not voluntarily clean up the child process of the working environment, there must be a parent process helper wait or waitpid function to complete the cleanup work. Assume that the parent process does not do cleanup work. Once the child process is introduced, it will become a zombie process, the system assumes that too many zombie processes will affect system performancefunction 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 wait for the PID to be developed, such as fire 1, which means waiting for all the sub-processes Status Parameter is the outgoing parameter, which holds the exit status 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 a child process exits or not, it returns immediately .examples of zombie process generation:
#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 status. 0 indicates normal exit, other number indicates error, process abnormal end







































Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Linux Multi-learning 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.