⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 process.texi

📁 一个C源代码分析器
💻 TEXI
📖 第 1 页 / 共 2 页
字号:
@node Processes@chapter Processes@cindex process@dfn{Processes} are the primitive units for allocation of systemresources.  Each process has its own address space and (usually) onethread of control.  A process executes a program; you can have multipleprocesses executing the same program, but each process has its own copyof the program within its own address space and executes itindependently of the other copies.@cindex child process@cindex parent processProcesses are organized hierarchically.  Each process has a @dfn{parentprocess} which explicitly arranged to create it.  The processes createdby a given parent are called its @dfn{child processes}.  A childinherits many of its attributes from the parent process.This chapter describes how a program can create, terminate, and controlchild processes.  Actually, there are three distinct operationsinvolved: creating a new child process, causing the new process toexecute a program, and coordinating the completion of the child processwith the original program.The @code{system} function provides a simple, portable mechanism forrunning another program; it does all three steps automatically.  If youneed more control over the details of how this is done, you can use theprimitive functions to do each step individually instead.@menu* Running a Command::           The easy way to run another program.* Process Creation Concepts::   An overview of the hard way to do it.* Process Identification::      How to get the process ID of a process.* Creating a Process::          How to fork a child process.* Executing a File::            How to make a process execute another program.* Process Completion::          How to tell when a child process has completed.* Process Completion Status::   How to interpret the status value                                  returned from a child process.* BSD Wait Functions::  	More functions, for backward compatibility.* Process Creation Example::    A complete example program.@end menu@node Running a Command@section Running a Command@cindex running a commandThe easy way to run another program is to use the @code{system}function.  This function does all the work of running a subprogram, butit doesn't give you much control over the details: you have to waituntil the subprogram terminates before you can do anything else.@comment stdlib.h@comment ANSI@deftypefun int system (const char *@var{command})@pindex shThis function executes @var{command} as a shell command.  In the GNU Clibrary, it always uses the default shell @code{sh} to run the command.In particular, it searches the directories in @code{PATH} to findprograms to execute.  The return value is @code{-1} if it wasn'tpossible to create the shell process, and otherwise is the status of theshell process.  @xref{Process Completion}, for details on how thisstatus code can be interpreted.@pindex stdlib.hThe @code{system} function is declared in the header file@file{stdlib.h}.@end deftypefun@strong{Portability Note:} Some C implementations may not have anynotion of a command processor that can execute other programs.  You candetermine whether a command processor exists by executing@w{@code{system (NULL)}}; if the return value is nonzero, a commandprocessor is available.The @code{popen} and @code{pclose} functions (@pxref{Pipe to aSubprocess}) are closely related to the @code{system} function.  Theyallow the parent process to communicate with the standard input andoutput channels of the command being executed.@node Process Creation Concepts@section Process Creation ConceptsThis section gives an overview of processes and of the steps involved increating a process and making it run another program.@cindex process ID@cindex process lifetimeEach process is named by a @dfn{process ID} number.  A unique process IDis allocated to each process when it is created.  The @dfn{lifetime} ofa process ends when its termination is reported to its parent process;at that time, all of the process resources, including its process ID,are freed.@cindex creating a process@cindex forking a process@cindex child process@cindex parent processProcesses are created with the @code{fork} system call (so the operationof creating a new process is sometimes called @dfn{forking} a process).The @dfn{child process} created by @code{fork} is a copy of the original@dfn{parent process}, except that it has its own process ID.After forking a child process, both the parent and child processescontinue to execute normally.  If you want your program to wait for achild process to finish executing before continuing, you must do thisexplicitly after the fork operation, by calling @code{wait} or@code{waitpid} (@pxref{Process Completion}).  These functions give youlimited information about why the child terminated---for example, itsexit status code.A newly forked child process continues to execute the same program asits parent process, at the point where the @code{fork} call returns.You can use the return value from @code{fork} to tell whether the programis running in the parent process or the child.@cindex process imageHaving several processes run the same program is only occasionallyuseful.  But the child can execute another program using one of the@code{exec} functions; see @ref{Executing a File}.  The program that theprocess is executing is called its @dfn{process image}.  Startingexecution of a new program causes the process to forget all about itsprevious process image; when the new program exits, the process exitstoo, instead of returning to the previous process image.@node Process Identification@section Process IdentificationThe @code{pid_t} data type represents process IDs.  You can get theprocess ID of a process by calling @code{getpid}.  The function@code{getppid} returns the process ID of the parent of the currentprocess (this is also known as the @dfn{parent process ID}).  Yourprogram should include the header files @file{unistd.h} and@file{sys/types.h} to use these functions.@pindex sys/types.h@pindex unistd.h@comment sys/types.h@comment POSIX.1@deftp {Data Type} pid_tThe @code{pid_t} data type is a signed integer type which is capableof representing a process ID.  In the GNU library, this is an @code{int}.@end deftp@comment unistd.h@comment POSIX.1@deftypefun pid_t getpid (void)The @code{getpid} function returns the process ID of the current process.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun pid_t getppid (void)The @code{getppid} function returns the process ID of the parent of thecurrent process.@end deftypefun@node Creating a Process@section Creating a ProcessThe @code{fork} function is the primitive for creating a process.It is declared in the header file @file{unistd.h}.@pindex unistd.h@comment unistd.h@comment POSIX.1@deftypefun pid_t fork (void)The @code{fork} function creates a new process.If the operation is successful, there are then both parent and childprocesses and both see @code{fork} return, but with different values: itreturns a value of @code{0} in the child process and returns the child'sprocess ID in the parent process.If process creation failed, @code{fork} returns a value of @code{-1} inthe parent process.  The following @code{errno} error conditions aredefined for @code{fork}:@table @code@item EAGAINThere aren't enough system resources to create another process, or theuser already has too many processes running.  This means exceeding the@code{RLIMIT_NPROC} resource limit, which can usually be increased;@pxref{Limits on Resources}.@item ENOMEMThe process requires more space than the system can supply.@end table@end deftypefunThe specific attributes of the child process that differ from theparent process are:@itemize @bullet@itemThe child process has its own unique process ID.@itemThe parent process ID of the child process is the process ID of itsparent process.@itemThe child process gets its own copies of the parent process's open filedescriptors.  Subsequently changing attributes of the file descriptorsin the parent process won't affect the file descriptors in the child,and vice versa.  @xref{Control Operations}.  However, the file positionassociated with each descriptor is shared by both processes;@pxref{File Position}.@itemThe elapsed processor times for the child process are set to zero;see @ref{Processor Time}.@itemThe child doesn't inherit file locks set by the parent process.@c !!! flock locks shared@xref{Control Operations}.@itemThe child doesn't inherit alarms set by the parent process.@xref{Setting an Alarm}.@itemThe set of pending signals (@pxref{Delivery of Signal}) for the childprocess is cleared.  (The child process inherits its mask of blockedsignals and signal actions from the parent process.)@end itemize @comment unistd.h@comment BSD@deftypefun pid_t vfork (void)The @code{vfork} function is similar to @code{fork} but on systems itis more efficient; however, there are restrictions you must follow touse it safely.While @code{fork} makes a complete copy of the calling process'saddress space and allows both the parent and child to executeindependently, @code{vfork} does not make this copy.  Instead, thechild process created with @code{vfork} shares its parent's addressspace until it calls exits or one of the @code{exec} functions.  In themeantime, the parent process suspends execution.You must be very careful not to allow the child process created with@code{vfork} to modify any global data or even local variables sharedwith the parent.  Furthermore, the child process cannot return from (ordo a long jump out of) the function that called @code{vfork}!  Thiswould leave the parent process's control information very confused.  Ifin doubt, use @code{fork} instead.Some operating systems don't really implement @code{vfork}.  The GNU Clibrary permits you to use @code{vfork} on all systems, but actuallyexecutes @code{fork} if @code{vfork} isn't available.  If you followthe proper precautions for using @code{vfork}, your program will stillwork even if the system uses @code{fork} instead.@end deftypefun@node Executing a File@section Executing a File@cindex executing a file@cindex @code{exec} functionsThis section describes the @code{exec} family of functions, for executinga file as a process image.  You can use these functions to make a childprocess execute a new program after it has been forked.@pindex unistd.hThe functions in this family differ in how you specify the arguments,but otherwise they all do the same thing.  They are declared in theheader file @file{unistd.h}.@comment unistd.h@comment POSIX.1@deftypefun int execv (const char *@var{filename}, char *const @var{argv}@t{[]})The @code{execv} function executes the file named by @var{filename} as anew process image.The @var{argv} argument is an array of null-terminated strings that isused to provide a value for the @code{argv} argument to the @code{main}function of the program to be executed.  The last element of this arraymust be a null pointer.  By convention, the first element of this arrayis the file name of the program sans directory names.  @xref{ProgramArguments}, for full details on how programs can access these arguments.The environment for the new process image is taken from the@code{environ} variable of the current process image; see@ref{Environment Variables}, for information about environments.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int execl (const char *@var{filename}, const char *@var{arg0}, @dots{})This is similar to @code{execv}, but the @var{argv} strings arespecified individually instead of as an array.  A null pointer must bepassed as the last such argument.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int execve (const char *@var{filename}, char *const @var{argv}@t{[]}, char *const @var{env}@t{[]})This is similar to @code{execv}, but permits you to specify the environmentfor the new program explicitly as the @var{env} argument.  This shouldbe an array of strings in the same format as for the @code{environ} variable; see @ref{Environment Access}.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int execle (const char *@var{filename}, const char *@var{arg0}, char *const @var{env}@t{[]}, @dots{})This is similar to @code{execl}, but permits you to specify theenvironment for the new program explicitly.  The environment argument ispassed following the null pointer that marks the last @var{argv}argument, and should be an array of strings in the same format as forthe @code{environ} variable.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int execvp (const char *@var{filename}, char *const @var{argv}@t{[]})The @code{execvp} function is similar to @code{execv}, except that itsearches the directories listed in the @code{PATH} environment variable(@pxref{Standard Environment}) to find the full file name of afile from @var{filename} if @var{filename} does not contain a slash.This function is useful for executing system utility programs, becauseit looks for them in the places that the user has chosen.  Shells use itto run the commands that users type.@end deftypefun@comment unistd.h@comment POSIX.1@deftypefun int execlp (const char *@var{filename}, const char *@var{arg0}, @dots{})This function is like @code{execl}, except that it performs the samefile name searching as the @code{execvp} function.@end deftypefunThe size of the argument list and environment list taken together mustnot be greater than @code{ARG_MAX} bytes.  @xref{General Limits}.  Inthe GNU system, the size (which compares against @code{ARG_MAX})includes, for each string, the number of characters in the string, plusthe size of a @code{char *}, plus one, rounded up to a multiple of thesize of a @code{char *}.  Other systems may have somewhat differentrules for counting.These functions normally don't return, since execution of a new programcauses the currently executing program to go away completely.  A valueof @code{-1} is returned in the event of a failure.  In addition to theusual file name syntax errors (@pxref{File Name Errors}), the following@code{errno} error conditions are defined for these functions:@table @code@item E2BIGThe combined size of the new program's argument list and environmentlist is larger than @code{ARG_MAX} bytes.  The GNU system has nospecific limit on the argument list size, so this error code cannotresult, but you may get @code{ENOMEM} instead if the arguments are toobig for available memory.@item ENOEXECThe specified file can't be executed because it isn't in the right format.@item ENOMEMExecuting the specified file requires more storage than is available.@end tableIf execution of the new file succeeds, it updates the access time fieldof the file as if the file had been read.  @xref{File Times}, for moredetails about access times of files.The point at which the file is closed again is not specified, butis at some point before the process exits or before another processimage is executed.Executing a new process image completely changes the contents of memory,copying only the argument and environment strings to new locations.  Butmany other attributes of the process are unchanged:@itemize @bullet@itemThe process ID and the parent process ID.  @xref{Process Creation Concepts}.@itemSession and process group membership.  @xref{Concepts of Job Control}.@itemReal user ID and group ID, and supplementary group IDs.  @xref{ProcessPersona}.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -