| Skip Navigation Links | |
| Exit Print View | |
![]() | man pages section 3: Basic Library Functions Oracle Solaris 11 Information Library |
enable_extended_FILE_stdio(3C)
posix_spawnattr_getschedparam(3C)
posix_spawnattr_getschedpolicy(3C)
posix_spawnattr_getsigdefault(3C)
posix_spawnattr_getsigignore_np(3C)
posix_spawnattr_getsigmask(3C)
posix_spawnattr_setschedparam(3C)
posix_spawnattr_setschedpolicy(3C)
posix_spawnattr_setsigdefault(3C)
posix_spawnattr_setsigignore_np(3C)
posix_spawnattr_setsigmask(3C)
posix_spawn_file_actions_addclose(3C)
posix_spawn_file_actions_addclosefrom_np(3C)
posix_spawn_file_actions_adddup2(3C)
posix_spawn_file_actions_addopen(3C)
posix_spawn_file_actions_destroy(3C)
posix_spawn_file_actions_init(3C)
pthread_attr_getdetachstate(3C)
pthread_attr_getinheritsched(3C)
pthread_attr_getschedparam(3C)
pthread_attr_getschedpolicy(3C)
pthread_attr_setdetachstate(3C)
pthread_attr_setinheritsched(3C)
pthread_attr_setschedparam(3C)
pthread_attr_setschedpolicy(3C)
pthread_barrierattr_destroy(3C)
pthread_barrierattr_getpshared(3C)
pthread_barrierattr_setpshared(3C)
pthread_condattr_getpshared(3C)
pthread_condattr_setpshared(3C)
pthread_cond_reltimedwait_np(3C)
pthread_key_create_once_np(3C)
pthread_mutexattr_getprioceiling(3C)
pthread_mutexattr_getprotocol(3C)
pthread_mutexattr_getpshared(3C)
pthread_mutexattr_getrobust(3C)
pthread_mutexattr_setprioceiling(3C)
pthread_mutexattr_setprotocol(3C)
pthread_mutexattr_setpshared(3C)
pthread_mutexattr_setrobust(3C)
pthread_mutex_getprioceiling(3C)
pthread_mutex_reltimedlock_np(3C)
pthread_mutex_setprioceiling(3C)
pthread_rwlockattr_destroy(3C)
pthread_rwlockattr_getpshared(3C)
pthread_rwlockattr_setpshared(3C)
pthread_rwlock_reltimedrdlock_np(3C)
pthread_rwlock_reltimedwrlock_np(3C)
pthread_rwlock_timedrdlock(3C)
pthread_rwlock_timedwrlock(3C)
rctlblk_get_enforced_value(3C)
- parse long command options
#include <getopt.h>intgetopt_long(intargc,char * const *argv,const char *shortopts,const struct option *longopts,int *indexptr);
intgetopt_long_only(intargc,char * const *argv,const char *shortopts,const struct option *longopts,int *indexptr);
intgetopt_clip(intargc,char * const *argv,const char *shortopts,const struct option *longopts,int *indexptrextern char *optarg;extern intoptind,opterr,optopt;
These functions are provided as a porting aid for GNU/Freeware/OpenBSD utilities. Thegetopt_long() function is intended to be as closely compatible with the GNUand OpenBSD implementations as possible, but since these public implementations differ insome corner cases, it is not possible to be fully compatible with both.The differences are enumerated in the NOTES section.
Thegetopt_long() function is an aid for implementing the GNU command lineargument conventions. See the GNU documentation for the details of these conventions(glibc 2.2.3). Note that the GNU conventions are not POSIX-conforming. Most notably,the GNU conventions allow for optional option-arguments and do not enforce that operandsmust follow options on the command line.
Thegetopt_clip() function provides an interface similar togetopt_long() except that itimplements the Sun CLIP convention, which is slightly more restrictive than theGNU/Freeware conventions. CLIP is modeled after the GNU/Freeware conventions but removes POSIX violationsand syntactic ambiguities (seeIntro(1)). Specifically,getopt_clip() is a command line parserthat can be used by applications that follow the Command Line Interface Paradigmor CLIP syntax guidelines 3, 4, 5, 6, 7, 9, 10, 15,and 16. The remaining guidelines are not addressed bygetopt_clip() and arethe responsibility of the application.
Thegetopt_long() function is similar togetopt(3C) except that it accepts optionsin two forms: words and characters, also referred to as long options andshort options.
Thegetopt_long() function can be used in two ways. In the firstway, every long option understood by the program is mapped to asingle character that is usually a corresponding short option. Theoption structureis used only to translate from long options to short options. In thesecond way, a long option sets aflag specified in theoptionstructure, or stores a pointer to the command line argument in theaddress passed to it for options that take arguments. These two methodsapply individually to each long option. Both methods can be used in thesame application.
Thegetopt_long() function accepts command lines that interleave options and operands. Thegetopt_long() function reorders the elements of theargv argument such that whenall command line arguments have been processed, all operands follow options (and theiroption-arguments) in theargv array andoptind points to the first operand.The order of options relative to other options and operands relative toother operands is maintained. The argument “--” is accepted as a delimiter indicatingthe end of options. No argument reorder occurs past this delimiter. Argumentreordering can not be unambiguously performed in all cases. Thegetopt_long() functiondepends on a number of internal heuristics to perform the reordering. Theargc andargv arguments are the argument count and argument array aspassed tomain() (seeexec(2)).
Theshortopts argument contains the short-option characters recognized by the command usingthese functions. If a letter is followed by a colon (:), theoption is expected to have an option-argument that should be separated fromit by white space. If a character is followed by two colons (::),the option takes an optional option-argument. Any text after the option nameit is returned inoptarg; otherwise,optarg is set to 0. Awhitespace character can never be used to separate an optional option-argument from itsassociated option. Ifshortopts contains the character “W” followed by a semicolon(;), then-Wfoo is treated as the long option --foo.
If the first character of theshortopts argument is the plus sign(+),getopt_long() enforces the POSIX requirement that operands follow options on thecommand line by returning -1 and stopping argument processing upon encountering thefirst operand (or “--”). This behavior can also be specified by setting theenvironment variablePOSIXLY_CORRECT.
A hyphen (-) as the first character of theshortopts argument specifiesthat options and operands can be intermixed inargv but no argumentreordering is performed. Operands are returned as arguments to option `\1', andoption processing does not stop until “--” or the end ofargv isfound.
If the first character of theshortopts argument (after a potential plusor minus character) is a colon (:), a colon is returned bygetopt_long() in response to a missing argument; otherwise, a question mark (?)is returned for this condition.
Thelongopts argument describes the long options to accept. It isan array ofstruct option structures, one for each long option. The arrayis terminated with an element containing all zeros.
Thestruct option structure contains the following members:
Contains a pointer to the name of the option.
Specifies whether the option takes an argument. The possible values, defined in <getopt.h>, areno_argument,optional_argument, andrequired_argument.
Contains the address of anint variable that is the flag for this option. The value contained in val is stored in this location to indicate that the option was seen. Ifflag is a null pointer, then the value contained inval is returned when this option is encountered, otherwise zero is returned.
Contains the value to be stored at the variable pointed to byflag or returned bygetopt_long() ifflag is a null pointer.
For any long option,getopt_long() returns the index in the arraylongoptsof the options definition by storing it inindexptr. The name ofthe option can be retrieved withlongopts[(*indexptr)].name. Long options can be distinguishedeither by the values in theirval members or by their indices.Theindexptr variable can also distinguish long options that set flags. Thevalue ofindexptr after encountering a short option is undefined.
If an option has an argument, theoptarg global variable is setto point to the start of the option argument on return fromgetopt_long(); otherwise it is set to null. A long option can takean argument in one of two forms: --option=arg or --option arg. If thelong option argument is optional, only the “--option=arg” form can be usedto specify the option argument. No argument is specified by the simpleform “--option”. The form “--option=” specifies an empty string as the option argument.
Long-option names can be abbreviated if the abbreviation is unique or anexact match for some defined option. An exact match takes precedence overan abbreviated match. Thus, iffoo andfoobar are acceptable long-option names,then specifying --foo on the command line always matches the former. Specifying --f or --fo would not be accepted as a match foreither.
Thegetopt_long() function places inoptind theargv index of the nextargument to be processed. Theoptind global variable is external and isinitialized to 1 before the first call togetopt_long(). When all options havebeen processed (that is, up to the first non-option argument),getopt_long() returns-1. The special option “--” (two hyphens) can be used to delimitthe end of the options; when it is encountered, -1 is returnedand “—” is skipped. This ooption is useful in delimiting non-option arguments thatbegin with “-” (hyphen).
Ifgetopt_long() encounters a short option charactershortopts string or a longoption not described in thelongopts array, it returns the question mark(?) character. It also returns a question mark (?) character in response toa missing option argument unless the first character ofshortopts is acolon (:) (or the second character, if the first character is eithera plus (+) or a minus (-)), in which case it returnsa colon (:). In either case, if the application has not setopterr to 0 and the first character ofshortopts is not a colon(:),getopt_long() prints a diagnostic message tostderr.
Thegetopt_long_only() function is equivalent to thegetopt_long() function except that itallows the user of the application to pass long options with onlya single hyphen (-) instead of “--”. The “--” prefix is stillrecognized. However, when a single hyphen (-) is encountered,getopt_long_only() attempts to matchthis argument to a long option, including abbreviations of the long option.If a long option starts with the same character as a shortoption, a single hyphen followed by that character (and no other characters) willbe recognized as a short option. Use ofgetopt_long_only() is strongly discouragedby Sun and GNU for new applications.
The behavior ofgetopt_clip() differs from that ofgetopt_long() in the followingways:
Thegetopt_clip() function does not perform argument reordering. Thegetopt_clip() function always enforces the POSIX behavior that all options should precede operands on the command line. Specifically,getopt_clip() does not reorder arguments but returns -1 and stops processing upon encountering the first operand argument.
The environment variablePOSIXLY_CORRECT is ignored (thegetopt_clip() function behaves as though it were set.)
The plus and minus characters do not have a special meaning as the first character of theshortopts argument. They are treated as any other character (other than the colon) would be treated.
Optional option-arguments are not allowed. The behavior ofgetopt_clip() whenoptional_argument is specified as the value ofhas_arg in thelongopts argument or double colons are included in theshortopts argument is unspecified.
Long-option abbreviations are not recognized.
Short options are required to have at least one long-option equivalent. That is, each character inshortopts must appear as theval member in one or moreoption structures. Similarly, each long option must have a short option equivalent, meaning that theval member of eachoption structure must appear in theshortopts string. If these requirements are not met,getopt_clip() returns -1 and setserrno toEINVAL.
For short options (other than-W whenW; is inshortopts), thesefunctions return the next option character specified on the command line. Forlong options, the value returned by these functions depends upon the valueof theflag structure element for the identified option. Ifflag isNULL, the value contained in theval structure element for thelong option encountered on the command line is returned. Otherwise, thesefunctions return 0 (and the value specified in theval member for thelong option is stored into the location pointed to byflag). WhenW; is inshortopts and-W is encountered in the command lineand the option argument to-W matches a long-option name, the return statefrom these functions is as if the long option had been encountered.However, if no argument is specified to the long option,optarg isset to the option argument of-W (the long-option name or unique prefix).If the option argument of-W does not match a long option(or unique prefix), the return state is as for any other shortoption.
A colon (:) is returned ifgetopt_long() detects a missing argument andthe first character ofshortopts (other than a possible initial “+” or“-”) was a colon (':').
A question mark (?) is returned ifgetopt_long() encounters an option letternot included inshortopts or detects a missing argument and the firstcharacter ofshortopts (other than a possible initial “+” or “-”) was nota colon (:).
Thegetopt_clip() function expects all short options to have one or morelong-option equivalent and all long options to have one short option equivalent(see NOTES for details). If proper equivalents are not found,getopt_clip() returns-1 and setserrno toEINVAL.
Thegetopt_clip() function will fail if:
A short option does not have at least one long-option equivalent, or a long option does not have at least one short-option equivalent.
Example 1 Example usinggetopt().
#include <unistd.h>#include <getopt.h>/* Flag set by `--verbose'. */static int verbose_flag;intmain (int argc, char **argv){ int c; while (1) { static struct option long_options[] = { /* These options set a flag. */ {"verbose", no_argument, &verbose_flag, 1}, {"brief", no_argument, &verbose_flag, 0}, /* The following options don't set a flag. */ {"add", no_argument, NULL, 'a'}, {"append", no_argument, NULL, 'b'}, {"delete", required_argument, NULL, 'd'}, {"create", required_argument, NULL, 'c'}, {"file", required_argument, NULL, 'f'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "abc:d:f:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* (In this example) only options which set */ /* a flag return zero, so do nothing. */ break; case 'a': puts ("option --add (-a)\n"); break; case 'b': puts ("option --append (-b)\n"); break; case 'c': printf ("option --create (-c) with value `%s'\n", optarg); break; case 'd': printf ("option --delete (-d) with value `%s'\n", optarg); break; case 'f': printf ("option --file (-f) with value `%s'\n", optarg); break; case '?': /* getopt_long already printed an error message. */ break; default: abort (); } } /* Instead of reporting `--verbose' and `--brief' as they are encountered, we report the final status resulting from them. */ if (verbose_flag) puts ("verbose flag is set"); /* Print any remaining command line arguments (not options). */ if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); putchar ('\n'); } exit (0);}See environ(5) for descriptions of the following environment variables that affect theexecution ofgetopt_long():LANG,LC_ALL, andLC_MESSAGES.
When set (and the first character of theshortopts argument is neither a plus or minus sign), the POSIX rule that all operands must follow all options is enforced. Option processing terminates when the first operand is encountered. Thegetopt_clip() function ignores the setting ofPOSIXLY_CORRECT and always behaves as if it were set.
Determine the locale for the interpretation of sequences of bytes as characters inshortopts and thelongopts[].name structure members.
Thegetopt_long() function does not fully check for mandatory arguments because thereis no unambiguous algorithm to do so. Given an option stringa:band the input-a -b,getopt_long() assumes that-b is the mandatory argument tothe-a option and not that-a is missing a mandatory argument.Indeed, the only time a missing option argument can be reliably detectedis when the option is the final option on the command lineand is not followed by any command arguments.
Seeattributes(5) for descriptions of the following attributes:
|
Intro(1),getopts(1),getopt(3C),getsubopt(3C),gettext(3C),setlocale(3C),attributes(5),environ(5),standards(5)
Use ofgetopt_long() is discouraged for applications targeted strictly for Solaris. Itshould be used only for applications targeted at Solaris and platforms thatadhere to the GNU command line conventions. Thegetopt_long_only() function is provided bySolaris and GNU for legacy applications and its use is discouraged byboth current conventions.
The differences between the Solaris/GNU and OpenBSD versions of these functions areas follows:
The handling of the hyphen (-) as the first character of the option string in presence of the environment variablePOSIXLY_CORRECT:
Operands are returned as arguments to option '\\1', and option processing does not stop until “--” or the end ofargv is found.
obeysPOSIXLY_CORRECT and stops at the first non-option.
The handling of the hyphen (-) within theshortopts parameter string when not the first character.
treats a single hyphen (-) on the command line as an operand.
treats a single hyphen (-) on the command line as an option. BSD recognizes this behavior as incorrect, but maintains it for compatibility.
The return value in the event of a missing argument if the first character after “+” or “-” in the option string is not a colon (:)
returns “?”.
returns “:” (since OpenBSD's getopt does).
The settingoptopt for long options withflag !=NULL:
setsoptopt toval.
setsoptopt to 0 (sinceval would never be returned).
The setting ofoptarg for long options without an argument that are invoked with-W (W; in option string):
setsoptarg to the option name (the argument of-W).
setsoptarg toNULL (the argument of the long option).
The handling of-W with an argument that is not (a prefix to) a known long option (W; in option string):
returns 'W' withoptarg set to the unknown option.
treats as an error (unknown option) and returns “?” withoptopt set to 0 andoptarg set toNULL.
The error messages are different (all).
The implementations do not permute the argument vector at the same points in the calling sequence. The aspects normally used by the caller (ordering after -1 is returned, value ofoptind relative to current positions) are the same. Applications should not depend upon the ordering of the argument vector before -1 is returned.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.Legal Notices | ![]() ![]() |