Fork and exec Functions

Source: Internet
Author: User

#include<unistd.h>pid_t fork(void);                                                                                                      返回:在子进程中为0,在父进程中为子进程IO,若出错则为-1

The most difficult thing about fork is to call it once, but it returns twice. It is returned once in the calling process (called the parent process). The returned value is the ID of the newly-Derived Process (called the child process). The returned value is once again in the child process, and the returned value is 0. therefore, the returned value indicates whether the current process is a child process or a parent process.

The reason fork returns 0 in the child process instead of the parent process ID is that any child process has only one parent process, and the child process can always get the parent process ID through getppid. On the contrary, a parent process can have many sub-processes and cannot obtain the ID of each sub-process. If the parent process wants to track the IDs of all child processes, it must record the returned values of each call to fork.

All descriptors opened before fork is called in the parent process are shared by the child process after fork is returned.. We will see that the network server uses this feature: the parent process calls fork after the accept is called. The accepted connected socket is then shared between the Process and the sub-process. Generally, the child process then reads and writes the connected socket, and the parent process closes the connected socket.

Two typical fork usage.

(1) A process creates a copy of itself, so that each copy can process a specific operation while another copy executes other tasks. This is a typical usage of network servers.

(2) One process wants to execute another program. Since the only way to create a new process is to call fork, the process first calls fork to create a copy of itself, and then one of the copies (usually a child process) call exec to replace itself with a new program. This is a typical usage of programs such as shell.

The only way for executable program files stored on the hard disk to be executed by UNIX is to call one of the Six exec functions by an existing process. Exec replaces the current process image with a new program file, and the new program is usually executed from the main function. The process ID does not change. The process that calls exec is called a calling process, and the newly executed program is called a new program.

The difference between the Six exec functions is: (a) whether the program file to be executed is specified by the file name (filename) or by the path name (pathname); (B) the parameters of the new program are listed one by one or referenced by a pointer array. (c) Whether to pass the environment of the calling process to the new program or specify a new environment for the new program.

Exec function family

Function Family description

The fork () function is used to create a new sub-process. The sub-process almost copies all the content of the parent process. However, how can this newly created sub-process be executed? The exec function family provides a method to start execution of another program in the process. It can locate the executable file based on the specified file name or directory name and use it to replace the data segment, code segment, and stack segment of the original calling process. After the execution, all the content of the original calling process except the process number is replaced by the new process. In addition, the executable file can be either a binary file or any executable script file in Linux.

In Linux, there are two main scenarios for using the exec function family:

● When a process deems itself unable to make any contribution to the system and users, it can call any function in the exec function family to regenerate itself.

● If a process wants to execute another program, it can call the fork () function to create a new process and then call any function in the exec function family, this looks like a new process is generated by executing an application (which is quite common ).

Function Family syntax

In fact, in Linux, there are no exec () functions, but six functions starting with exec, with syntax nuances. The following table lists the syntax of the six member functions in the exec function family:

These functions are returned to the caller only when an error occurs. Otherwise, the starting point of control that will be passed to the new program is usually the main function.

These six functions have minor differences in terms of function names and syntax-based rules. Below we will compare the methods for finding executable files, passing parameters, and environment variables.

● Search method: the first four functions in Table 1 are all in the complete file directory path. The last two functions (two functions ending with P) can only provide the file name, the system automatically searches for the path specified by the environment variable "$ path.

● Parameter passing method: the exec function family provides two parameter passing Methods: one is to list the parameters one by one, and the other is to construct an array of pointers for all parameters. It is distinguished by a 5th-bit Letter of the function name. the letter "L" (list) represents the way parameters are listed one by one. Its syntax is const char * ARG; the letter "V" (vector) indicates that all parameters are passed in an integral constructor array. Its syntax is char * const argv []. The parameters here are actually all the Command Option strings (including the executable program command itself) required by the user when using the executable file ). Note that these parameters must end with null.

● Environment variable: the exec function family can default the system environment variable or pass in the specified environment variable. Here, the two functions execle () and execve () ending with "E" (Environment) can specify the environment variables used by the current process in envp.

Table 2 further summarizes the function names and corresponding syntaxes in these six functions, mainly pointing out the meanings indicated by the corresponding bits in the function names, remember these six functions in this table.

In fact, only execve () is actually called by the system among the six functions, and the other five are database functions. They will eventually call the execve () System Call. When using the exec function family, you must add an error judgment statement. Exec is easy to fail. The most common causes are:

① The file or path cannot be found, and errno is set to enoent.

② Array argv and envp forget to end with null. At this time, errno is set to efaul.

③ There is no operation permission for the executable file, and errno is set to eacces.

Basic lab

Lab 1

This experiment describes how to use the file name to find executable files and the parameter list. The function used here is execlp (). The program code is as follows:

In this program, you first use the fork () function to create a sub-process, and then use the execlp () function in the sub-process. As you can see, the parameter list lists the command names and options used in shell, and when the file name is used for search, the system searches for the executable file in the default path environment variable.

Run the command GCC execlp. C-o execlp after compilation. The result is as follows:

Run the Env command to view the path name of the environment variable.

The execution result of this program is the same as that of the command "PS-Ef" directly entered in the shell. Of course, different results may occur at different times in different systems.

Lab 2

The functions implemented in this experiment are the same as those in Experiment 1. Different functions are used. This experiment uses the complete file directory to find the corresponding executable file. Note: The directory must start with "/"; otherwise, the directory is treated as a file name. The program code is as follows:

Write and save the source file, run the command: GCC execl. C-o execl to compile, and then run the command:./execl. The experiment result is the same as that of Experiment 1.

Lab 3

In this experiment, the execle () function is used to add environment variables to the newly created sub-process. Here, "env" is the command to view the environment variables of the current process. The experiment code is as follows:

After saving the source file, run the command: GCC execle. C-o execle, and then run the command:./execle. The execution result is as follows:

Lab 4

The implementation function of this experiment is the same as that of experiment 3. Different from the execve () function, parameters are transmitted by constructing a pointer array. Note that the parameter list must use null as the end identifier, the experiment code is as follows:

Write and save the source file, run the command: GCC execve. C-o execve, and then run the command:./execve. The result is as follows:

Fork and exec Functions

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.