📄 library_22.html
字号:
<!-- This HTML file has been created by texi2html 1.27 from library.texinfo on 3 March 1994 --><TITLE>The GNU C Library - Process Startup and Termination</TITLE><P>Go to the <A HREF="library_21.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_21.html">previous</A>, <A HREF="library_23.html" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_23.html">next</A> section.<P><H1><A NAME="SEC385" HREF="library_toc.html#SEC385" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC385">Process Startup and Termination</A></H1><A NAME="IDX1622"></A><P><DFN>Processes</DFN> 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.<P>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.<P><A NAME="IDX1623"></A><A NAME="IDX1624"></A><H2><A NAME="SEC386" HREF="library_toc.html#SEC386" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC386">Program Arguments</A></H2><A NAME="IDX1625"></A><P>The system starts a C program by calling the function <CODE>main</CODE>. Itis up to you to write a function named <CODE>main</CODE>---otherwise, youwon't even be able to link your program without errors.<P>You can define <CODE>main</CODE> either to take no arguments, or to take twoarguments that represent the command line arguments to the program, likethis:<P><PRE>int main (int <VAR>argc</VAR>, char *<VAR>argv</VAR>[])</PRE><A NAME="IDX1626"></A><A NAME="IDX1627"></A><P>The command line arguments are the whitespace-separated tokens given inthe shell command used to invoke the program; thus, in <SAMP>`cat foobar'</SAMP>, the arguments are <SAMP>`foo'</SAMP> and <SAMP>`bar'</SAMP>. The only way aprogram can look at its command line arguments is via the arguments of<CODE>main</CODE>. If <CODE>main</CODE> doesn't take arguments, then you cannot getat the command line.<P>The value of the <VAR>argc</VAR> argument is the number of command linearguments. The <VAR>argv</VAR> 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</VAR> counts this element. A nullpointer always follows the last element: <CODE><VAR>argv</VAR>[<VAR>argc</VAR>]</CODE>is this null pointer.<P>For the command <SAMP>`cat foo bar'</SAMP>, <VAR>argc</VAR> is 3 and <VAR>argv</VAR> hasthree elements, <CODE>"cat"</CODE>, <CODE>"foo"</CODE> and <CODE>"bar"</CODE>.<P>If the syntax for the command line arguments to your program is simpleenough, you can simply pick the arguments off from <VAR>argv</VAR> 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</CODE> to do the parsing.<P><A NAME="IDX1628"></A><A NAME="IDX1629"></A><A NAME="IDX1630"></A><H3><A NAME="SEC387" HREF="library_toc.html#SEC387" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC387">Program Argument Syntax Conventions</A></H3><P>POSIX recommends these conventions for command line arguments.<CODE>getopt</CODE> (see section <A HREF="library_22.html#SEC388" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_22.html#SEC388">Parsing Program Options</A>) makes it easy to implement them.<P><UL><LI>Arguments are options if they begin with a hyphen delimiter (<SAMP>`-'</SAMP>).<P><LI>Multiple options may follow a hyphen delimiter in a single token ifthe options do not take arguments. Thus, <SAMP>`-abc'</SAMP> is equivalent to<SAMP>`-a -b -c'</SAMP>.<P><LI>Option names are single alphanumeric characters (as for <CODE>isalnum</CODE>;see section <A HREF="library_4.html#SEC55" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_4.html#SEC55">Classification of Characters</A>).<P><LI>Certain options require an argument. For example, the <SAMP>`-o'</SAMP> commandof the <CODE>ld</CODE> command requires an argument--an output file name.<P><LI>An option and its argument may or may not appear as separate tokens. (Inother words, the whitespace separating them is optional.) Thus,<SAMP>`-o foo'</SAMP> and <SAMP>`-ofoo'</SAMP> are equivalent.<P><LI>Options typically precede other non-option arguments.<P>The implementation of <CODE>getopt</CODE> 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</VAR> array. This behavior isnonstandard; if you want to suppress it, define the<CODE>_POSIX_OPTION_ORDER</CODE> environment variable. See section <A HREF="library_22.html#SEC394" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_22.html#SEC394">Standard Environment Variables</A>.<P><LI>The argument <SAMP>`--'</SAMP> terminates all options; any following argumentsare treated as non-option arguments, even if they begin with a hyphen.<P><LI>A 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.<P><LI>Options may be supplied in any order, or appear multiple times. Theinterpretation is left up to the particular application program.</UL><A NAME="IDX1631"></A><P>GNU adds <DFN>long options</DFN> to these conventions. Long options consistof <SAMP>`--'</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.<P>To specify an argument for a long option, write<SAMP>`--<VAR>name</VAR>=<VAR>value</VAR>'</SAMP>. This syntax enables a long option toaccept an argument that is itself optional.<P>Eventually, the GNU system will provide completion for long option namesin the shell.<P><A NAME="IDX1632"></A><A NAME="IDX1633"></A><A NAME="IDX1634"></A><H3><A NAME="SEC388" HREF="library_toc.html#SEC388" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC388">Parsing Program Options</A></H3><P>Here are the details about how to call the <CODE>getopt</CODE> function. Touse this facility, your program must include the header file<TT>`unistd.h'</TT>.<A NAME="IDX1635"></A><P><A NAME="IDX1636"></A><U>Variable:</U> int <B>opterr</B><P>If the value of this variable is nonzero, then <CODE>getopt</CODE> 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</CODE>does not print any messages, but it still returns the character <CODE>?</CODE>to indicate an error.<P><A NAME="IDX1637"></A><U>Variable:</U> int <B>optopt</B><P>When <CODE>getopt</CODE> 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.<P><A NAME="IDX1638"></A><U>Variable:</U> int <B>optind</B><P>This variable is set by <CODE>getopt</CODE> to the index of the next elementof the <VAR>argv</VAR> array to be processed. Once <CODE>getopt</CODE> 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</CODE>.<P><A NAME="IDX1639"></A><U>Variable:</U> char * <B>optarg</B><P>This variable is set by <CODE>getopt</CODE> to point at the value of theoption argument, for those options that accept arguments.<P><A NAME="IDX1640"></A><U>Function:</U> int <B>getopt</B> <I>(int <VAR>argc</VAR>, char **<VAR>argv</VAR>, const char *<VAR>options</VAR>)</I><P>The <CODE>getopt</CODE> function gets the next option argument from theargument list specified by the <VAR>argv</VAR> and <VAR>argc</VAR> arguments.Normally these values come directly from the arguments received by<CODE>main</CODE>.<P>The <VAR>options</VAR> 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>`:'</SAMP>) to indicate that it takes arequired argument.<P>If the <VAR>options</VAR> argument string begins with a hyphen (<SAMP>`-'</SAMP>), thisis treated specially. It permits arguments that are not options to bereturned as if they were associated with option character <SAMP>`\0'</SAMP>.<P>The <CODE>getopt</CODE> function returns the option character for the nextcommand line option. When no more option arguments are available, itreturns <CODE>-1</CODE>. There may still be more non-option arguments; youmust compare the external variable <CODE>optind</CODE> against the <VAR>argc</VAR>parameter to check this.<P>If the option has an argument, <CODE>getopt</CODE> returns the argument bystoring it in the varables <VAR>optarg</VAR>. You don't ordinarily need tocopy the <CODE>optarg</CODE> string, since it is a pointer into the original<VAR>argv</VAR> array, not into a static area that might be overwritten.<P>If <CODE>getopt</CODE> finds an option character in <VAR>argv</VAR> that was notincluded in <VAR>options</VAR>, or a missing option argument, it returns<SAMP>`?'</SAMP> and sets the external variable <CODE>optopt</CODE> to the actualoption character. If the first character of <VAR>options</VAR> is a colon(<SAMP>`:'</SAMP>), then <CODE>getopt</CODE> returns <SAMP>`:'</SAMP> instead of <SAMP>`?'</SAMP> toindicate a missing option argument. In addition, if the externalvariable <CODE>opterr</CODE> is nonzero (which is the default), <CODE>getopt</CODE>prints an error message.<P><H3><A NAME="SEC389" HREF="library_toc.html#SEC389" tppabs="http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_toc.html#SEC389">Example of Parsing Arguments with <CODE>getopt</CODE></A></H3><P>Here is an example showing how <CODE>getopt</CODE> is typically used. Thekey points to notice are:<P><UL><LI>Normally, <CODE>getopt</CODE> is called in a loop. When <CODE>getopt</CODE> returns<CODE>-1</CODE>, indicating no more options are present, the loop terminates.<P><LI>A <CODE>switch</CODE> statement is used to dispatch on the return value from<CODE>getopt</CODE>. In typical use, each case just sets a variable thatis used later in the program.<P><LI>A second loop is used to process the remaining non-option arguments.</UL><P><PRE>#include <unistd.h>#include <stdio.h>int main (int argc, char **argv){ int aflag = 0; int bflag = 0; char *cvalue = NULL; int index; int c; opterr = 0; while ((c = getopt (argc, argv, "abc:")) != -1) switch (c) { case 'a': aflag = 1; break; case 'b': bflag = 1; break; case 'c': cvalue = optarg; break; case '?': if (isprint (optopt)) fprintf (stderr, "Unknown option `-%c'.\n", optopt); else fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: abort (); } printf ("aflag = %d, bflag = %d, cvalue = %s\n", aflag, bflag, cvalue); for (index = optind; index < argc; index++) printf ("Non-option argument %s\n", argv[index]); return 0;}</PRE><P>Here are some examples showing what this program prints with differentcombinations of arguments:<P><PRE>% 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 = fooNon-option argument arg1% testopt -a -- -baflag = 1, bflag = 0, cvalue = (null)Non-option argument -b% testopt -a -aflag = 1, bflag = 0, cvalue = (null)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -