Create a sub-process execution task in Linux

Source: Internet
Author: User

Create a sub-process execution task in Linux

The Linux operating system depends on Process Creation to meet user needs. For example, if you enter a command, the shell process creates a new process, and the new process runs another copy of the shell and runs the command entered by the user. In Linux, a new process is created by calling the fork/vfork system. This article describes how to use fork/vfork system call to create a new process and use the exec family function to execute tasks in the new process.

Fork system call

To create a process, the most basic system call is fork:

# include <unistd.h>pid_t fork(void);pid_t vfork(void);

When fork is called, The system creates a new process that is the same as the current process. Generally, the original process is called a parent process, and the newly created process is called a child process. A child process is a copy of the parent process. The child process obtains the same data as the parent process, but the same parent process uses different data and stack segments. The child process inherits most attributes from the parent process, but also modifies some attributes. The following table compares the attribute differences between parent and child processes:

Inherited attributes Difference
Uid, gid, euid, egid Process ID
Process Group ID Parent process ID
SESSION ID Sub-process running time record
Offset of the opened file and file The parent process locks the file.
Control Terminal  
Set User ID and set group ID tag  
Root directory and current directory  
Default File Permission mask  
Accessible memory segments  
Environment variable and other resource allocation  

The following is a common demo that demonstrates the working principle of fork (the author's environment is Ubuntu 16.04 desktop ):

#include <sys/types.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>int main(void){    pid_t pid;    char *message;    int n;    pid = fork();    if(pid < 0)    {        perror("fork failed");        exit(1);    }    if(pid == 0)    {        printf("This is the child process. My PID is: %d. My PPID is: %d.\n", getpid(), getppid());    }    else    {        printf("This is the parent process. My PID is %d.\n", getpid());    }    return 0;}

Save the above Code to the forkdemo. c file, and execute the following command to compile:

$ gcc forkdemo.c -o forkdemo

Then run the compiled forkdemo program:

$ ./forkdemo

The fork function is called once and returns twice. It is called once in the parent process and child process. The returned value in the parent process is the PID of the child process, and the returned value in the child process is 0. After the returned value is 0, the fork function is executed. If the fork function fails to be called, the returned value is-1.
We will find that the fork function's return value design is still very clever. If the fork function returns 0 in the child process, the child process can still call the getpid function to obtain its own PID, or call the getppid function to obtain the parent process PID. You can use the getpid function in the parent process to get your own PID. If you want to get the PID of the child process, the only way is to record the return value of the fork function.
Note: When the forkdemo program is executed, the output changes. The parent process information may be printed or printed first.

Vfork system call

The vfork System Call and fork system call functions are basically the same. The process created by the vfork System Call shares the memory address space of its parent process, but does not completely copy the data segment of the parent process, but shares the data segment with the parent process. To prevent the parent process from overwriting the data required by the child process, the parent process is blocked by the vfork call until the child process exits or executes a new program. Because the parent process is suspended when the vfork function is called, if we use the vfork function to replace the fork function in forkdemo, the order of output information will not change when the program is executed.

Sub-processes created using vfork generally execute new programs through the exec family function. Next, let's take a look at the exec functions.

Exec Functions

After using fork/vfork to create a sub-process, the same program as the parent process is executed (but different code branches may be executed ), sub-processes often need to call an exec family function to execute another program. When a process calls the exec family function, the user space code and data of the process are completely replaced by the new program and executed from the beginning of the new program. Calling the exec family function does not create a new process, so the PID of the process does not change before and after the exec family function is called.

There are six exec functions:

#include <unistd.h>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[]);int execve(const char *path, char *const argv[], char *const envp[]);

If the function name contains the letter "l", the number of parameters is uncertain. If the function name contains the letter "v", the string array pointer argv is used to point to the parameter list.
The function name contains the letter "p", indicating that you can automatically search for the program to be executed in the PATH specified by the Environment Variable PATH.
The function name contains the letter "e" and has one more envp parameter than other functions. This parameter is a string array pointer used to specify environment variables. When calling such a function, you can set the environment variables of the sub-process and store them in the string array pointed to by the envp parameter.

In fact, only execve is a real system call, and the other five functions eventually call execve. The relationship between these functions is shown in (this figure is from the Internet ):

Features of exec functions: When you call an exec function, a new program is loaded into the current process. After the exec family function is called, the Code executed in the process is completely different from the previous code, so the code after the exec function is called will not be executed.

Execute tasks in sub-Processes

The following describes how to execute the ls command in a sub-process through the vfork and execve functions:

# Include <sys/types. h> # include <unistd. h> # include <stdio. h> # include <stdlib. h> int main (void) {pid_t pid; if (pid = vfork () <0) {printf ("vfork error! \ N "); exit (1) ;}else if (pid = 0) {printf (" Child process PID: % d. \ n ", getpid (); char * argv [] = {" ls ","-al ","/home ", NULL }; char * envp [] = {"PATH =/bin", NULL}; if (execve ("/bin/ls", argv, envp) <0) {printf ("subprocess error"); exit (1) ;}// the sub-process either exits from the ls command or from the preceding exit (1) statement exit // so the code execution path will never go here, and the following printf statement will not be executed printf ("You shoshould never see this message. ");} else {printf (" Parent process PID: % d. \ n ", getpid (); sleep (1);} return 0 ;}

Save the above Code to the file subprocessdemo. c, and run the following command to compile:

$ gcc subprocessdemo.c -o subprocessdemo

Then run the compiled subprocessdemo program:

$ ./subprocessdemo

Summary

Fork/vfork functions and exec functions are important concepts in Linux. This article tries to use a simple demo to demonstrate the basic usage of these functions, to provide some intuitive understanding of the concept of the parent process and child process in Linux.

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.