Introduction to Linux process programming (2)

Source: Internet
Author: User
Article title: Introduction to Linux process programming (2 ). Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Abstract: This section describes some basic operations on a process. through this section, we will learn how to generate a sub-process, how the process changes its execution image, and synchronization of parent and child processes. We also learned some basic concepts of parallel programs and how to compile simple parallel programs.
  
2. general process operations
  
The previous section introduces some basic concepts about processes. starting from this section, we will introduce some examples to illustrate the system calls of related processes. This section describes some basic operations on a process. through this section, we will learn how to generate a sub-process, how the process changes its execution image, and synchronization of parent and child processes. We also learned some basic concepts of parallel programs and how to compile simple parallel programs.
  
2.1 fork system call
  
Fork is used to create a sub-process. The creation process is described in the previous section. Now, we will introduce a system call to vfork, which is generated because it realizes that the performance can be improved by not copying all pages of the parent process when creating a child process. This call assumes that exec will be called immediately after vfork is called, so that you do not need to copy all the page tables of the parent process. Because it does not copy the page table, it is faster than the fork call. In some systems, fork also uses other methods to improve performance. a typical method is to add "copy at Write Time ". In this fork call, when a child process is generated, the child process does not copy all pages of the parent process, but copies all pages of the parent process at write time. The child process shares all pages of the parent process. When a parent or child process writes a page, a protective error occurs and the page is copied. This not only improves the kernel performance, but also improves memory utilization.
  
The declaration formats of fork and vfork are as follows:
  
?? Pid_t fork (void );
?? Pid_t vfork (void );
  
Add the following header files to programs called by the system:
  
?? # Include
  
When the call is successful, the call returns the child process PID to the parent process and the child process returns 0. If the call fails,-1 is returned to the parent process, and no child process is created.
  
The following error code errno may be set when an error occurs:
  
EAGAIN: the system calls fork and cannot obtain enough memory to copy the parent process page table. Or the user is a super user but the table is full, or the user is not a super user but reaches the maximum number of processes that a single user can execute.
ENOMEM: there is not enough space for creating a new process. this error indicates that there is not enough space allocated to the necessary kernel structure.
The following is a simple example of fork call. In this example, a child process is generated. the parent process prints the PID of itself and the child process, and the child process prints its own PID and the PID of the parent process.
  
Note: the parent process opens a file. Both parent and child processes can operate on the file. the parent and child processes of the program write a row into the file.
  
?? # Include
?? # Include
?? # Include
?? # Include
?? # Include
?? # Include
?? # Include
?? # Include
?? Extern int errno;
?? Int main ()
?? {
?? Char buf [100];
?? Pid_t cld_pid;
?? Int fd;
?? Int status;
  
?? If (fd = open ("temp", O_CREAT | O_TRUNC | O_RDWR, S_IRWXU) =-1)
?? {
???? Printf ("open error % d", errno );
???? Exit (1 );
??}
?? Strcpy (buf, "This is parent process write ");
  
?? If (cld_pid = fork () = 0)
?? {/* Here is the code executed by the sub-process */
???? Strcpy (buf, "This is child process write ");
???? Printf ("This is child process ");
???? Printf ("My PID (child) is % d", getpid ();/* print the ID of the process */
???? Printf ("My parent PID is % d", getppid ();/* print the ID of the parent process */
???? Write (fd, buf, strlen (buf ));
???? Close (fd );
???? Exit (0 );
??}
?? Else
?? {/* Code executed by the parent process */
???? Printf ("This is parent process ");
???? Printf ("My PID (parent) is % d", getpid ();/* print the ID of the current process */
???? Printf ("My child PID is % d", cld_pid);/* print the ID of the sub-process */
???? Write (fd, buf, strlen (buf ));
???? Close (fd );
??}
?? Wait (& status);/* What if there is no such sentence? */
?? Return 0;
}
  
Let's take a look at the program running result. assume that the source file is named fork. c:
  
?? [Root @ wapgw/root] # gcc-o fork. c
?? [Root @ wapgw/root] #./fork
?? This is parent process
?? This is child process
?? My PID (child) is 5258
?? My parent PID is 5257
?? My PID (parent) is 5257
?? My child PID is 5258
?? [Root @ wapgw/root] #
  
From the preceding running results, we can see that the process is scheduled. after the parent process prints the first line, the CPU schedules the sub-process and prints the next three lines. the sub-process ends, schedule the execution of the parent process (other processes may be scheduled). after the execution of the parent process, return the control to the shell program. The last line is the prompt output by the shell program.
  
See what is in the temp file.
  
?? [Root @ wapgw/root] # more temp
?? This is child process write
?? This is parent process write
?? [Root @ wapgw/root] #
  
Now we will slightly modify the program. Comment out the wait call and let's see what the results will look like. If you execute multiple times for scheduling, you will see the following results:
  
?? [Root @ wapgw/root] # vi fork. c // comment out the wait call
?? [Root @ wapgw/root] # gcc-o fork. c
?? [Root @ wapgw/root] #./fork
?? This is parent process
?? This is child process
?? My PID (parent) is 5282
?? My child PID is 5283
?? [Root @ wapgw/root] # My PID (child) is 5283
?? My parent PID is 1
?? [Root @ wapgw/root] #
  
The first line is the output of the parent process, the second line is the output of the child process, and the third and fourth lines are the output of the parent process. in this case, the parent process has no wait call, stops without waiting for the child process. In the following line, "[root @ wapgw/root] #" indicates the end of the parent process and the shell output prompt when the control is returned to the shell. Then the CPU calls the sub-process and the PID of the output sub-process is 5283. Note: the ID of the parent process output by the lower-face process is 1, because its parent process is finished, and the kernel gives it to process 1 (process init) for management, for more information about this process, see the previous section. The output result sequence is related to the process scheduling sequence. the result of your own test may be different from the sequence in the example. please analyze it on your own.
  
2.2 exec system call
  
The system calls exec to execute an executable file to replace the execution image of the current process. It should be noted that the call did not generate a new process, but instead replaced the text of the original process on the basis of the original process. The process ID remains unchanged before and after the call. But the execution program has changed (the execution command sequence has changed ). It has six calling modes, which are not exactly the same as described below. Their declaration formats are as follows:
  
?? 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 execve (const char * filename, char * const argv [], char * const envp []);
?? Int execvp (const char * file, char * const argv []);
  
Add the following header files and external variables to programs that use these system calls:
  
?? # Include
?? Extern char ** environ;
  
Next we will first detail one of them, and then give the difference between them. In the execve system call, the path parameter is the file to be executed, the argv parameter is the parameter to be passed to the file, and the envp parameter is the environment variable to be passed to the file. After the file indicated by the path parameter replaces the execution image of the original process, the file path starts to be executed, and the argv and envp parameters are passed to the process. The following is a simple example.
  
Let's take a look at the environment variables before describing the example of a system call to execve. LINUX introduces the concept of environment to allow users to use Shell conveniently and flexibly. The environment is some data. you can change the data, add new data, or delete some data. These data are called environment variables. Because they define the user's work environment and can be modified at the same time. Each user can have their own different environment variables. you can use the env command (without parameters) to browse the environment variables, the output format and variable name vary with Shell and system configuration. In the following example, all parameters and environment variables passed to the process are printed:
  
?? # Include
?? # Include
?? Extern char ** environ;
?? Int main (int argc, char * argv [])
?? {
?? Int I;
?? Printf ("Argument :");
?? For (I = 0; I ?? Printf ("Environment :");
?? For (I = 0; environ [I]! = NULL; I ++) printf ("% s", environ [I]);
??}
  
The screen copy during execution is as follows:
  
?? [Root @ wapgw/root] # gcc-o example. c
?? [Root @ wapgw/root] #./example test
?? Argument:
?? Arg0 is./example
?? Arg1 is test
  
?? Environment:
?? PWD =/root
?? REMOTEHOST = cjm
?? HOSTNAME = wapgw
?? HOME =/root
??.......................
?? SSH_ASKPASS =/usr/libexec/ssh/gnome-ssh-askpass
?? PATH =/usr/local/sbin:/usr/local/bin:
?? /Sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/B
Related Article

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.