📄 startup.texi
字号:
@node Process Startup@chapter Process Startup and Termination@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.This chapter explains what your program should do to handle the startupof a process, to terminate its process, and to receive information(arguments and the environment) from the parent process.@menu* Program Arguments:: Parsing your program's command-line arguments.* Environment Variables:: How to access parameters inherited from a parent process.* Program Termination:: How to cause a process to terminate and return status information to its parent.@end menu@node Program Arguments@section Program Arguments@cindex program arguments@cindex command line arguments@cindex arguments, to program@cindex program startup@cindex startup of program@cindex invocation of program@cindex @code{main} function@findex mainThe system starts a C program by calling the function @code{main}. Itis up to you to write a function named @code{main}---otherwise, youwon't even be able to link your program without errors.In ANSI C you can define @code{main} either to take no arguments, or totake two arguments that represent the command line arguments to theprogram, like this:@smallexampleint main (int @var{argc}, char *@var{argv}[])@end smallexample@cindex argc (program argument count)@cindex argv (program argument vector)The command line arguments are the whitespace-separated tokens given inthe shell command used to invoke the program; thus, in @samp{cat foobar}, the arguments are @samp{foo} and @samp{bar}. The only way aprogram can look at its command line arguments is via the arguments of@code{main}. If @code{main} doesn't take arguments, then you cannot getat the command line.The value of the @var{argc} argument is the number of command linearguments. The @var{argv} argument is a vector of C strings; itselements are the individual command line argument strings. The filename of the program being run is also included in the vector as thefirst element; the value of @var{argc} counts this element. A nullpointer always follows the last element: @code{@var{argv}[@var{argc}]}is this null pointer.For the command @samp{cat foo bar}, @var{argc} is 3 and @var{argv} hasthree elements, @code{"cat"}, @code{"foo"} and @code{"bar"}.If the syntax for the command line arguments to your program is simpleenough, you can simply pick the arguments off from @var{argv} by hand.But unless your program takes a fixed number of arguments, or all of thearguments are interpreted in the same way (as file names, for example),you are usually better off using @code{getopt} to do the parsing.In Unix systems you can define @code{main} a third way, using three arguments:@smallexampleint main (int @var{argc}, char *@var{argv}[], char *@var{envp})@end smallexampleThe first two arguments are just the same. The third argument@var{envp} gives the process's environment; it is the same as the valueof @code{environ}. @xref{Environment Variables}. POSIX.1 does notallow this three-argument form, so to be portable it is best to write@code{main} to take two arguments, and use the value of @code{environ}.@menu* Argument Syntax:: By convention, options start with a hyphen.* Parsing Options:: The @code{getopt} function.* Example of Getopt:: An example of parsing options with @code{getopt}.* Long Options:: GNU suggests utilities accept long-named options. Here is how to do that.* Long Option Example:: An example of using @code{getopt_long}.@end menu@node Argument Syntax@subsection Program Argument Syntax Conventions@cindex program argument syntax@cindex syntax, for program arguments@cindex command argument syntaxPOSIX recommends these conventions for command line arguments.@code{getopt} (@pxref{Parsing Options}) makes it easy to implement them.@itemize @bullet@itemArguments are options if they begin with a hyphen delimiter (@samp{-}).@itemMultiple options may follow a hyphen delimiter in a single token ifthe options do not take arguments. Thus, @samp{-abc} is equivalent to@samp{-a -b -c}.@itemOption names are single alphanumeric characters (as for @code{isalnum};see @ref{Classification of Characters}).@itemCertain options require an argument. For example, the @samp{-o} commandof the @code{ld} command requires an argument---an output file name.@itemAn option and its argument may or may not appear as separate tokens. (Inother words, the whitespace separating them is optional.) Thus,@samp{-o foo} and @samp{-ofoo} are equivalent.@itemOptions typically precede other non-option arguments.The implementation of @code{getopt} in the GNU C library normally makesit appear as if all the option arguments were specified before all thenon-option arguments for the purposes of parsing, even if the user ofyour program intermixed option and non-option arguments. It does thisby reordering the elements of the @var{argv} array. This behavior isnonstandard; if you want to suppress it, define the@code{_POSIX_OPTION_ORDER} environment variable. @xref{StandardEnvironment}.@itemThe argument @samp{--} terminates all options; any following argumentsare treated as non-option arguments, even if they begin with a hyphen.@itemA token consisting of a single hyphen character is interpreted as anordinary non-option argument. By convention, it is used to specifyinput from or output to the standard input and output streams.@itemOptions may be supplied in any order, or appear multiple times. Theinterpretation is left up to the particular application program.@end itemize@cindex long-named optionsGNU adds @dfn{long options} to these conventions. Long options consistof @samp{--} followed by a name made of alphanumeric characters anddashes. Option names are typically one to three words long, withhyphens to separate words. Users can abbreviate the option names aslong as the abbreviations are unique.To specify an argument for a long option, write@samp{--@var{name}=@var{value}}. This syntax enables a long option toaccept an argument that is itself optional.Eventually, the GNU system will provide completion for long option namesin the shell.@node Parsing Options@subsection Parsing Program Options@cindex program arguments, parsing@cindex command arguments, parsing@cindex parsing program argumentsHere are the details about how to call the @code{getopt} function. Touse this facility, your program must include the header file@file{unistd.h}.@pindex unistd.h@comment unistd.h@comment POSIX.2@deftypevar int opterrIf the value of this variable is nonzero, then @code{getopt} prints anerror message to the standard error stream if it encounters an unknownoption character or an option with a missing required argument. This isthe default behavior. If you set this variable to zero, @code{getopt}does not print any messages, but it still returns the character @code{?}to indicate an error.@end deftypevar@comment unistd.h@comment POSIX.2@deftypevar int optoptWhen @code{getopt} encounters an unknown option character or an optionwith a missing required argument, it stores that option character inthis variable. You can use this for providing your own diagnosticmessages.@end deftypevar@comment unistd.h@comment POSIX.2@deftypevar int optindThis variable is set by @code{getopt} to the index of the next elementof the @var{argv} array to be processed. Once @code{getopt} has foundall of the option arguments, you can use this variable to determinewhere the remaining non-option arguments begin. The initial value ofthis variable is @code{1}.@end deftypevar@comment unistd.h@comment POSIX.2@deftypevar {char *} optargThis variable is set by @code{getopt} to point at the value of theoption argument, for those options that accept arguments.@end deftypevar@comment unistd.h@comment POSIX.2@deftypefun int getopt (int @var{argc}, char **@var{argv}, const char *@var{options})The @code{getopt} function gets the next option argument from theargument list specified by the @var{argv} and @var{argc} arguments.Normally these values come directly from the arguments received by@code{main}.The @var{options} argument is a string that specifies the optioncharacters that are valid for this program. An option character in thisstring can be followed by a colon (@samp{:}) to indicate that it takes arequired argument.If the @var{options} argument string begins with a hyphen (@samp{-}), thisis treated specially. It permits arguments that are not options to bereturned as if they were associated with option character @samp{\0}.The @code{getopt} function returns the option character for the nextcommand line option. When no more option arguments are available, itreturns @code{-1}. There may still be more non-option arguments; youmust compare the external variable @code{optind} against the @var{argc}parameter to check this.If the option has an argument, @code{getopt} returns the argument bystoring it in the varables @var{optarg}. You don't ordinarily need tocopy the @code{optarg} string, since it is a pointer into the original@var{argv} array, not into a static area that might be overwritten.If @code{getopt} finds an option character in @var{argv} that was notincluded in @var{options}, or a missing option argument, it returns@samp{?} and sets the external variable @code{optopt} to the actualoption character. If the first character of @var{options} is a colon(@samp{:}), then @code{getopt} returns @samp{:} instead of @samp{?} toindicate a missing option argument. In addition, if the externalvariable @code{opterr} is nonzero (which is the default), @code{getopt}prints an error message.@end deftypefun@node Example of Getopt@subsection Example of Parsing Arguments with @code{getopt}Here is an example showing how @code{getopt} is typically used. Thekey points to notice are:@itemize @bullet@itemNormally, @code{getopt} is called in a loop. When @code{getopt} returns@code{-1}, indicating no more options are present, the loop terminates.@itemA @code{switch} statement is used to dispatch on the return value from@code{getopt}. In typical use, each case just sets a variable thatis used later in the program.@itemA second loop is used to process the remaining non-option arguments.@end itemize@smallexample@include testopt.c.texi@end smallexampleHere are some examples showing what this program prints with differentcombinations of arguments:@smallexample% testoptaflag = 0, bflag = 0, cvalue = (null)% testopt -a -baflag = 1, bflag = 1, cvalue = (null)% testopt -abaflag = 1, bflag = 1, cvalue = (null)% testopt -c fooaflag = 0, bflag = 0, cvalue = foo% testopt -cfooaflag = 0, bflag = 0, cvalue = foo% testopt arg1aflag = 0, bflag = 0, cvalue = (null)Non-option argument arg1% testopt -a arg1aflag = 1, bflag = 0, cvalue = (null)Non-option argument arg1% testopt -c foo arg1aflag = 0, bflag = 0, cvalue = foo
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -