Linux creates child processes to perform tasks

Source: Internet
Author: User
Tags session id

The Linux operating system relies tightly on process creation to meet the needs of users. For example, as soon as a user enters a command, the shell process creates a new process, and the new process runs another copy of the shell and executes the command entered by the user. The Linux system is used to create a new process through fork/vfork system tuning. This article describes how to use the Fork/vfork system tune to create a new process and use the Exec family function to perform tasks in a new process.

Fork System Call

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

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

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

Inheritance Properties Difference
Uid,gid,euid,egid Process ID
Process Group ID Parent Process ID
SESSION ID Child process run time record
Offset of open files and files The parent process locks the file
Control Terminal
Set the user ID and set the group ID tag bit
root directory and current directory
Permission masks created by default for files
Accessible memory Segments
Environment variables and other resource allocation

Here is a common demo of how Fork works (the author's environment for Ubuntu 16.04 Desktop):

#include <sys/types.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>intMainvoid) {pid_t pid; Char*message; intN; PID=Fork (); if(PID <0) {perror ("Fork Failed"); Exit (1); }    if(PID = =0) {printf ("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 file 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 characterized by "call once, return two times": called once in the parent process and returned once in the parent and child processes. The return value returned in the parent process is the PID of the child process, and the return value when returned in the child process is 0, and the statement after the fork function call is executed after the return. If the fork function call fails, the return value is-1.
We think we'll find that the return value of the fork function is very clever. In the child process, the fork function returns 0, then the child process can still call the Getpid function to get its own PID, or call the Getppid function to get the parent process PID. In the parent process with the Getpid function can get their own PID, if you want the PID of the child process, the only way is to record the return value of the fork function.
Note: The output from the execution of the Forkdemo program can change, the information of the parent process may be printed first, or the child process information may be printed first.

vfork system Call

The functions of vfork system call and fork system call are basically the same. The vfork system calls the created process to share its parent process's memory address space, but does not fully replicate the data segment of the parent process, but rather shares its data segment with the parent process. To prevent the parent process from overriding 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 replace the fork function in Forkdemo with the Vfork function, the order in which the output information is executed will not change.

Child processes created with vfork typically execute new programs through the Exec family function. Let's look at the Exec family function first.

EXEC Family Functions

When you create a child process with fork/vfork, you execute the same program as the parent process (but it is possible to execute a different code branch), and the child process often needs to call an EXEC family function to execute another program. When the process calls the Exec family function, the user-space code and data for the process are completely replaced by the new program and executed at the beginning of the start. Calling the Exec family function does not create a new process, so the PID of the process before and after calling the Exec family function does not change.

There are six exec family functions:

#include <unistd.h>intEXECL (Const Char*path,Const Char*arg, ...);intEXECLP (Const Char*file,Const Char*arg, ...);intExecle (Const Char*path,Const Char*arg, ...,Char*Constenvp[]);intExecvConst Char*path,Char*Constargv[]);intEXECVP (Const Char*file,Char*Constargv[]);intExecve (Const Char*path,Char*ConstArgv[],Char*ConstEnvp[]);

The name of the function with the letter "L" means that its parameter number is indeterminate, with the letter "V" of the expression using a string array pointer argv to the parameter list.
The representation of the letter "P" in the function name automatically searches for the program to be executed in the path specified by the environment variable path.
A function whose name contains the letter "E" is one more parameter envp than the other function. This parameter is a string array pointer that specifies the environment variable. When such a function is called, the user can set the environment variable of the child process itself, which is stored in the string array pointed to by the parameter envp.

In fact, only EXECVE is a real system call, and the other five functions eventually call Execve. The relationships between these functions are as shown (this figure is from the Internet):

Features of the Exec family function: calling the Exec family function will load the new program into the current process. After calling the Exec family function, the code executing in the process is completely different from the previous one, so the code after the EXEC function call is not executed.

perform a task in a child process

Let's implement the LS command in a subprocess using the vfork and EXECVE functions:

#include <sys/types.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>intMainvoid) {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 child process either exits from the LS command or exits from the exit (1) statement above//so the code execution path is never going to get here, and the following printf statement will not be executedprintf"You should 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 file, and execute the following command to compile:

gcc subprocessdemo.c-o subprocessdemo

Then run the compiled Subprocessdemo program:

$./subprocessdemo

Summary

Both the Fork/vfork function and the Exec family function are very important concepts in Linux systems. This article attempts to demonstrate the basic usage of these functions through a simple demo, which provides some intuitive experience for understanding the concepts of parent and child processes in Linux systems.

Reference:

Linux C Programming One-stop learning
C Programming Guide in the Linux environment
Deep understanding of the Linux kernel

Linux creates child processes to perform tasks

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.